Scala String format named parameters (Winner: Ugliest Code) - string

I came up with a trick to use named parameters in Scala. Is there a better way? What are the downsides?
<x>
|CREATE OR REPLACE FUNCTION myFunction({columns.map(column => column.name).
mkString(",\n")})
|RETURNS BOOLEAN AS $$
|BEGIN
| -- more stuff
|END;
|$$ LANGUAGE 'plpgsql';
|</x>.text.stripMargin
Watch out for ampersands in the XML body; they need to be "quoted" as & or placed in braces like {"&"}. Do I win a prize for ugliest code? :-)

I think that if you need a string formater on this scale, you need a Builder or a templating engine, like Velocity. Incidentally, I've found Scala's good for builders and DSLs.

If you don't mind a compiler plugin, try Johannes Rudolph's Scala Enhanced Strings. I like it a lot.

Good news! Scala 2.10.0 introduced real, functional string interpolation!
The docs are available here: http://docs.scala-lang.org/overviews/core/string-interpolation.html
Here's a quick sample:
In Python, I used to do things like:
print "%(from)s -> %(to)s" % {"from": foo, "to": bar}
now, in Scala 2.10.0+, we can do this!
val from = "Foo"
val to = 256
println(s"$from -> $to") // Prints: Foo -> 256
There's also some format string support as well, which is pretty awesome:
val from = 10.00 // USD
val to = 984.30 // JPY
println(f"$$$from%.2f -> $to%.2fJPY") // Prints: $10.00 -> 984.30JPY
Since the second example has some minimal type expressiveness, it also gives us some basic type checking as well!
val from = 10.00
println(f"$$$from%d") // <-- Type error! Found "Double", required "Int"!

Related

What's the best way to convert an Int to a String in Julia?

I am using Julia (version 0.4.6), and the method that I have tried is:
a = 123
println( string(Int(a))*"b" )
Which looks long and awkward.
The other way I have tried is to write it to a file, and then read it. This is clearly worse. I wonder if there is a recommended method.
I'm not sure what you're trying to accomplish with the *"b" in your syntax, but for the rest of it:
julia> a = 123
123
julia> string(a)
"123"
julia> println(a)
123
The string() function can also take more arguments:
julia> string(a, "b")
"123b"
Note that it is not necessary to convert an Int type to an ASCIIString before calling println() on it - the conversion will occur automatically.
You can also insert (aka interpolate) integers (and certain other types) into strings using $:
julia> MyString = "my integer is $a"
"my integer is 123"
Performance Tip: The above methods can be quite convenient at times. But, if you will be performing many, many such operations and you are concerned about execution speed of your code, the Julia performance guide recommends against this, and instead in favor of the below methods:
You can supply multiple arguments to print() and println() which will operate on them exactly as string() operates on multiple arguments:
julia> println(a, "b")
123b
Or, when writing to file, you can similarly use, e.g.
open("/path/to/MyFile.txt", "w") do file
println(file, a, "b", 13)
end
or
file = open("/path/to/MyFile.txt", "a")
println(file, a, "b", 13)
close(file)
These are faster because they avoid needing to first form a string from given pieces and then output it (either to the console display or a file) and instead just sequentially output the various pieces.
Note: Answer reflects updates based on helpful comment from #Fengyang Wang.

Understanding String in Scala and the map method

I wrote the following simple example to understand how the map method works:
object Main{
def main (args : Array[String]) = {
val test = "abc"
val t = Vector(97, 98, 99)
println(test.map(c => (c + 1))) //1 Vector(98, 99, 100)
println(test.map(c => (c + 1).toChar)) //2 bcd
println(t.map(i => (i + 1))) //3 Vector(98, 99, 100)
println(t.map(i => (i + 1).toChar)) //4 Vector(b, c, d)
};
}
I didn't quite understand why bcd is printed at //2. Since every String is treated by Scala as being a Seq I thought that test.map(c => (c + 1).toChar) should have produced another Seq. As //1 suggests Vector(b, c, d). But as you can see, it didn't. Why? How does it actually work?
This is a feature of Scala collections (String in this case is treated as a collection of characters). The real explanation is quite complex, and involves understanding of typeclasses (I guess, this is why Haskell was mentioned in the comment), but the simple explanation is, well, not quite hard.
The point is, Scala collections library authors tried very hard to avoid code duplication. For example, the map function on String is actually defined here: scala.collection.TraversableLike#map. On the other hand, a naive approach to such task would make map return TraversableLike, not the original type the map was called on (it was the String). That's why they've came up with an approach that allows to avoid both code duplication and unnecessary type casting or too general return type.
Basically, Scala collections methods like map produce the type that is as close to the type it was called at as possible. This is achieved using a typeclass called CanBuildFrom. The full signature of the map looks as follows:
def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That
There is a lot of explanations what is a typeclass and CanBuildFrom around. I'd suggest looking here first: http://docs.scala-lang.org/overviews/core/architecture-of-scala-collections.html#factoring-out-common-operations. Another good explanation is here: Scala 2.8 CanBuildFrom
When you use map, this is what is happening : [List|Seq|etc].map([eachElement] => [do something])
map applies some operation to each element of the variable on the left hand-side : "abc".map(letter => letter + 1) will add 1 to each element of the String "abc". And each element of the String abc is called here "letter" (which is of type Char)
"abc" is a String, and as in C++, it is treated as an array of characters. But since test is of type String, the map function gives a String as well.
I tried the following :
val test2 : Seq[Char] = "abc"
but I still get a result of type String, I guess Scala does the conversion automatically from a Seq[Char] to a String
I hope it helped!

Lazy evaluation of chained functional methods in Groovy

What I've seen in Java
Java 8 allows lazy evaluation of chained functions in order to avoid performance penalties.
For instance, I can have a list of values and process it like this:
someList.stream()
.filter( v -> v > 0)
.map( v -> v * 4)
.filter( v -> v < 100)
.findFirst();
I pass a number of closures to the methods called on a stream to process the values in a collection and then only grab the first one.
This looks as if the code had to iterate over the entire collection, filter it, then iterate over the entire result and apply some logic, then filter the whole result again and finally grab just a single element.
In reality, the compiler handles this in a smarter way and optimizes the number of iterations required.
This is possible because no actual processing is done until findFirst is called. This way the compiler knows what I want to achieve and it can figure out how to do it in an efficient manner.
Take a look at this video of a presentation by Venkat Subramaniam for a longer explanation.
What I'd like to do in Groovy
While answering a question about Groovy here on StackOverflow I figured out a way to perform the task the OP was trying to achieve in a more readable manner. I refrained from suggesting it because it meant a performance decrease.
Here's the example:
collectionOfSomeStrings.inject([]) { list, conf -> if (conf.contains('homepage')) { list } else { list << conf.trim() } }
Semantically, this could be rewritten as
collectionOfSomeStrings.grep{ !it.contains('homepage')}.collect{ it.trim() }
I find it easier to understand but the readability comes at a price. This code requires a pass of the original collection and another iteration over the result of grep. This is less than ideal.
It doesn't look like the GDK's grep, collect and findAll methods are lazily evaluated like the methods in Java 8's streams API. Is there any way to have them behave like this? Is there any alternative library in Groovy that I could use?
I imagine it might be possible to use Java 8 somehow in Groovy and have this functionality. I'd welcome an explanation on the details but ideally, I'd like to be able to do that with older versions of Java.
I found a way to combine closures but it's not really what I want to do. I'd like to chain not only closures themselves but also the functions I pass them to.
Googling for Groovy and Streams mostly yields I/O related results. I haven't found anything of interest by searching for lazy evaluation, functional and Groovy as well.
Adding the suggestion as an answer taking cfrick's comment as an example:
#Grab( 'com.bloidonia:groovy-stream:0.8.1' )
import groovy.stream.Stream
List integers = [ -1, 1, 2, 3, 4 ]
//.first() or .last() whatever is needed
Stream.from integers filter{ it > 0 } map{ it * 4 } filter{ it < 15 }.collect()
Tim, I still know what you did few summers ago. ;-)
Groovy 2.3 supports jdk8 groovy.codehaus.org/Groovy+2.3+release+notes. your example works fine using groovy closures:
[-1,1,2,3,4].stream().filter{it>0}.map{it*4}.filter{it < 100}.findFirst().get()
If you can't use jdk8, you can follow the suggestion from the other answer or achieve "the same" using RxJava/RxGroovy:
#Grab('com.netflix.rxjava:rxjava-groovy:0.20.7')
import rx.Observable
Observable.from( [-1, 1, 2, 3, 4, 666] )
.filter { println "f1 $it"; it > 0 }
.map { println "m1 $it"; it * 4 }
.filter { println "f2 $it"; it < 100 }
.subscribe { println "result $it" }

Does Rust support Ruby-like string interpolation?

In Ruby I could do this.
aaa = "AAA"
bbb = "BBB #{aaa}"
puts(bbb)
> "BBB AAA"
The point of this syntax is eliminating repetition, and making it to feel like a shell script - great for heavy string manipulation.
Does Rust support this? Or have plan to support this? Or have some feature which can mimic this?
Rust has string formatting.
fn main() {
let a = "AAA";
let b = format!("BBB {}", a);
println(b);
}
// output: BBB AAA
In the Rust version, there is no additional repetition but you must explicitly call format!() and the inserted values are separated from the string. This is basically the same way that Python and C# developers are used to doing things, and the rationale is that this technique makes it easier to localize code into other languages.
The Rust mailing list has an archived discussion ([rust-dev] Suggestions) in which the different types of string interpolation are discussed.
This is available since Rust 1.58! Here's the syntax:
let (person, species, name) = ("Charlie Brown", "dog", "Snoopy");
// implicit named argument `person`
print!("Hello {person}");
// implicit named arguments `species` and `name`
format!("The {species}'s name is {name}.");
RFC 2795 is the original proposal.
As of Rust 1.58, you can take advantage of captured identifiers in format strings. That lets you do stuff like this:
let msg = "here";
let s = format!("Abc {msg}");
println!("Hi t{msg}"); // prints "Hi there"
println!("{s}"); // prints "Abc here"
This feature can be seen as a subset of string interpolation. Expressions like format!("Abc {a+b}") are not supported and it's unclear whether such a feature will ever be added. There have also been discussions on adding a subset of expressions for dotted paths, as in format!("Abc {foo.bar}").
Also note that the Rust 2021 Edition makes room for future additions to the language, such as f"hello {name}", which would allow for a much more concise string interpolation, comparable to most other modern languages.

How GOTO statement in Groovy?

I saw this nice blog post about a Scala continuations that 'emulates' a GOTO statement in the Scala language. (read more about Continuations here)
I would like to have the same in the programming language Groovy. I think it's possible within a Groovy compiler phase transformation.
I'm working on an Domain-Specific Language (DSL), and preferred embedded in Groovy. I would like to have the GOTO statement, because the DSL is an unstructured language (and is generated from workflow diagrams). I need a 'labeled' goto statement, not to line numbers.
The DSL is a language for workflow definitions, and because there are no restrictions for the arrows between nodes, a goto is needed. (or unreadable code with while etc)
As a beginner of Groovy and Scala I don't know If I can translate the Scala solution to Groovy, but I don think there are continuations in Groovy.
I'm looking for an algorithm/code for emulating labeled goto's in Groovy. One algorithm I had in mind is using eval repeatedly; doing the eval when your are at a goto.
The DSL is evaluated with an eval already.
I'm not looking for a 'while' loop or something, but rather translating this code so that it works (some other syntax is no problem)
label1:
a();
b();
goto label1;
PS:
I don't prefer the discussion if I should really use/want the GOTO statement. The DSL is a specification-language and is probably not coping with variables, efficiency etc.
PS2: Some other keyword then GOTO can be used.
You might want to tell a little bit more about the language you are trying to build, perhaps it's simple enough that dealing with transformations would be overengineering.
Playing with the AST is something groovy people have been doing for years and it's really powerful.
The spock framework guys rewrite the tests you create annotating the code with labels. http://code.google.com/p/spock/
Hamlet D'Arcy has given several presentations on the matter. Several posts can also be found on his blog. http://hamletdarcy.blogspot.com/
Cedric Champeau describes an interesting transformation he built and its evolution http://www.jroller.com/melix/
Probably missing lots of other guys but those I remember.
A possible starting points that you probably already know but are really useful. http://groovy.codehaus.org/Compile-time+Metaprogramming+-+AST+Transformations
http://groovy.codehaus.org/Building+AST+Guide
Long story short, I'd say its quite possible
You won't get anywhere trying this, as goto is a reserved word in Groovy (as it is in Java), so using it in your DSL will be problematic.
It's not a reserved word in Scala, so this isn't an issue
You can emulate if and goto with while loops. It won't be pretty, it will introduce lots of unnecessary code-blocks, but it should work for any function. There is some proof that this is always possible to rewrite code like that, but of course being possible does not mean it's nice or easy.
Basically you move all local variables to the beginning of the function and add a bool takeJump local variable. Then add a while(takeJump){+} pair for any goto+label pair and set the flag before the while and before the end of the while to the value you want.
But to be honest I don't recommend that approach. I'd rather use a library that allows me to build an AST with labels and gotos and then translates that directly to byte-code.
Or use some other language built on the java vm that does support goto. I'm sure there is such a language.
Just throwing this out there, perhaps you could have a scoped switch case
So if your DSL says this:
def foo() {
def x = x()
def y
def z
label a:
y = y(x)
if(y < someConst) goto a
label b:
z = y(z)
if(z > someConst) goto c
x = y(y(z+x))
z = y(x)
label c:
return z;
}
Your "compiler" can turn it into this:
def foo() {
String currentLABEL = "NO_LABEL"
while(SCOPED_INTO_BLOCK_0143) {
def x
def y
def z
def retval
switch(currentLABEL) {
case "NO_LABEL":
x = x()
case "LABEL_A"
y = y(x)
if(y < someConst) {
currentLABEL = "LABEL_A"
break
}
case "LABEL_B"
z = y(z)
if(z > someConst) {
currentLabel = "LABEL_C"
break
}
x = y(y(z+x))
z = y(x)
case "LABEL_C"
SCOPED_INTO_BLOCK_0143 = false
retval = z
}
}
return retval
}

Resources