After reading the docs and having a look through the source code, I'm a little unsure if there are any benefits of passing an explicit string to the fmt.Sprint function?
For example, will this:
return fmt.Sprint("this is a string")
be more beneficial than doing this:
return "this is a string"
Am I correct in thinking that this function works better with types that conform to the Stringer interface?
Yes, Sprint is pretty much useless for a single string, it should be used if you have a bunch of objects, Stringers or not. It just concatenates the string representations of them. from TFM:
Sprint formats using the default formats for its operands and returns
the resulting string. Spaces are added between operands when neither
is a string.
So if you have just one string it's useless. If you have many arguments, especially variadic, it sure beats doing something like fmt.Sprintf("%v %v %v", foo, bar, baz), especially if you don't know how many elements you have.
Related
I have user-provided format strings, and for each, I have a corresponding slice. For instance, I might have Test string {{1}}: {{2}} and ["number 1", "The Bit Afterwards"]. I want to generate Test string number 1: The Bit Afterwards from this.
The format of the user-provided strings is not fixed, and can be changed if need be. However, I cannot guarantee their sanity or safety; neither can I guarantee that any given character will not be used in the string, so any tags (like {} in my example) must be escapable. I also cannot guarantee that the same number of slice values will exist as tags in the template - for example, I might quite reasonably have Test string {{1}} and ["number 1", "another parameter", "yet another parameter"].
How can I efficiently format these strings, in accordance with the input given? They are for use as strings only, and don't require HTML, SQL or any other sort of escaping.
Things I've already considered:
fmt.Sprintf - two issues: 1) using it with user-provided templates is not ideal; 2) Sprintf does not play nicely with a number of parameters that doesn't match its format string, adding %!(EXTRA type=value) to the end.
The text/template library. This would work fine in theory, but I don't want to have to make users type out {{index .arr n}} for each and every one of their tags; in this case, I only ever need slice indexes.
The valyala/fasttemplate library. This is pretty much exactly what I'm looking for, but for the fact that it doesn't currently support escaping the delimiters it uses for its tags, at the time of writing. I've opened an issue for this, but I would have thought that there's already a solution to this problem somewhere - it doesn't feel like it's that unique.
Just writing my own parser for it. This would work... but, as above, I can't be the first person to have come across this!
Any advice or suggestions would be greatly appreciated.
I'm studying how to use the FIs and the lambda expressions and I was wondering if I could compare two objects but of a different type such as an Integer object and a String object. I've seen them, sometimes, being used interchangeably like a Char becoming and Integer or a CharSequence becoming a String. That made me think about comparing them since they all come from the Object superclass.
Thank you.
It's not entirely clear to me what you're asking here.
However, I would guess you saw a char being compared to an Integer when it was used to represent its Unicode value (cfr.: this question).
The relationship between String and CharSequence instead is that of a class implementing an interface (check this for more information)
I am learning Scala from Scala for the Impatient and Chapter 01 exercise has a problem
What do the take, drop, takeRight, and dropRight string functions
do? What advantage or disadvantage do they have over using substring?
The only advantage I see that drop(and flavors) will not throw IndexOutOfBoundsException
For example:
scala> "Hello World!" dropRight 100
res26: String = ""
scala> "Hello World!" substring 100
java.lang.StringIndexOutOfBoundsException: String index out of range: -88
at java.lang.String.substring(String.java:1919)
... 33 elided
What else? Memory efficient?
The main benefit is that it allows you to treat a String as a sequential collection of characters, much like any other Seq or List instance.
In fact, these methods (and other important transformational functions like map, flatMap and filter) are not implemented in String itself (which is, in fact, simply the Java String class, not a native-Scala class), but in the StringOps class (which extends StringLike -> ... -> SeqLike), and an implicit conversion ensures that a String is converted into a StringOps whenever you need access to these methods.
This means you can pass a String to a list-manipulation function and the function will receive a StringOps instance, work on it like any other SeqLike entity without needing to know it is actually a String, and hand back the results of the manipulation, which StringOps is designed to present back to you as a String.
If you know an entity is a String in a given piece of code, feel free to use the String-specific methods, but the availability of this implicit conversion means that you can also take advantage of a String's "character sequence"-like nature to treat it like any other list in situations where that may be convenient.
Seems that you are right. All these operations use StringOps.slice method, that delegates to String.substring method.
So, except for the overhead of wrapping string and performing bounds validation it's the same call to substring.
I want to implement a check function that given two strings s1 and s2 will check if s2 is the caesar cipher of s1 or not. the inter face needs to be looked like string->string->bool.
the problem is that I am not allowed to use any string functions other than String.length, so how can I solve it? i am not permitted any list array, iterations. Only recursions and pattern matching.
Please help me. And also can you tell me how I can write a substring function in ocaml other than the module function with the above restrictions?
My guess is that you are probably allowed to use s.[i] to get the ith character of string s. This is the same as String.get, but the instructor may not think of it in those terms. Without some form of getting the individual characters for the string, I believe that this is impossible. You should probably double check with your instructor to be sure, but I would be surprised if he had meant for you to be unable to separate a string into characters (which is something that you cannot do with pattern-matching alone in Ocaml).
Once you can get individual characters, the way to do it should be pretty clear (you do not need substring to traverse each string recursively).
If you still want to write substring, creating it would be complex since you don't have access to String.create or other similar functions. But you can write your own version of String.create using recursion, one character string literals (like "x"), the ability to set a character in a string to another (like s.[0] <- c), and string concatenation (s1 ^ s2). Again, of course, all of this is assuming that those operators are allowed to be used.
In scala, when you write out a string "Hello World" to a file it writes
Hello World
(note: no double quotes).
Lisp has a concept of print and write. One writes without the double quotes, the other includes them to make it easy to write out data structures and read them back later using the standard reader.
Is there anyway to do this in Scala?
With one string it is easy enough to format it - but with many deeply nested structures, it is nearly impossible.
For example, say I have
sealed trait PathSegment
case class P(x:String) extends PathSegment
case class V(x:Int) extends PathSegment
To create one does:
P("X")
or
V(0)
a list of these PathSegments prints as:
List(P(paths), P(/pets), P(get), P(responses), V(200))
I want this to print out as:
List(P("paths"), P("/pets"), P("get"), P("responses"), V(200))
In other words, I want strings (and characters), no matter where to occur in a structure to print out as "foo" or 'c'
That's what Serialization is about. Also, why JSON is popular.
Check out lift-json ( https://github.com/lift/lift/tree/master/framework/lift-base/lift-json/ ) for writing data out that will be parsed and read by another language. JSON is pretty standard in the web services world for request/response serialization and there are JSON libraries in just about every language.
To literally write out a string including double quotes, you can also do something like this:
"""
The word "apple" is in double quotes.
"""
I find a slightly more structured format like JSON more useful, and a library like lift-json does the right thing in terms of quoting Strings and not quoting Ints, etc.
I think you are looking for something like Javascript's eval() + JSON, and Python's eval(), str() and repr(). Essentially, you want Lispy symmetric meta-circular evaluation. Meaning you can transform data into source code, and evaluating that source code with give you back the same data, right?
AFAIK, there's no equivalent of eval() in Scala. Daniel Spiewak has talked about this here before. However, if you reeeeeealy want to. I suggest the following things:
Every collection object has 3 methods that will allow you to transform its data to a string representation anyway you want. There are mkString, addString and stringPrefix. Do something clever with them (think "decompiling" your in-memory ADTs back to source-code form) and you shall arrive to step 2). Essentially, you can transform a list of integers created by List(1,2,3) back to a string "List(1,2,3)". For more basic literals like a simple string or integer, you'll need to pimp the built-in types using implicits to provide them with these toString (I'm overloading the term here) helper methods.
Now you have your string representation, you can think about how to "interpret" or "evaluate" them. You will need an eval() function that create a new instance of a parser combinator that understands Scala's literals and reassemble the data structure for you.
Implementing this actually sounds fun. Don't forget to post back here if you've successfully implementing it. :)