Literal identifier in back ticks in scala - scala

As per the rule, "one or more of any character except a backquote, all enclosed in a pair of back-quotes", can be a valid identifier in scala. But the below one errors out.
scala> val `123` = "OneTwoThree"
<console>:5: error: ';' expected but double literal found.
lazy val $result = 123
^
<console>:9: error: ')' expected but double literal found.
"" + "123: String = " + _root_.scala.runtime.ScalaRunTime.replStringOf(123, 1000)
Am I missing something here ? Can someone please help. Thanks!

Gathering all the info in one answer so we can mark this question complete for the future visitors.
This is a known issue in the default Scala REPL. Follow the issue here
This currently only happens with numbers as per the ticket suggests. There likely is a sanitation issue.
This issue has been fixed in Ammomite that provides a 3rd party, open source REPL, with this commit. If you really need the REPL to support this feature, you can switch to Ammomite

Related

ReasonML: Unclosed "("

if(1<Array.length(Node.Process.argv)) {
Js.log("Too many arguments!");
}
The above 3-line ReasonML program does not compile:
Error: Unclosed "(" (opened line 1, column 2)
Tongue-in-cheek question: what is wrong? This is my pet peeve about ReasonML, because I counted parentheses and they do match.
I believe you need to insert a space after the <. As for the details of why this happens, I'm asking on Discord. I assume it has something to do with JSX.

What are the differences between these two Scala code segments regarding postfix toString method? [duplicate]

This question already has answers here:
toList on Range with suffix notation causes type mismatch
(2 answers)
Closed 5 years ago.
I am learning postfix unary operators in Scala.
The following can not compile:
val result = 43 toString
println(result)
However if I add one empty line inbetween the two lines, the code compile and produces right output:
val result = 43 toString
println(result)
What is the difference between these two segments?
BTW, I did not add "import scala.language.postfixOps".
Perhaps the issue is clearer if we use some other operator instead of toString.
// This parses as `List(1,2,3,4) ++ List(4,5,6)`
List(1,2,3,4) ++
List(4,5,6)
Basically, in order to make the above work, while also allowing things like foo ? (a postfix operator), Scala needs to know when it is OK to stop expecting a second argument (and accept that the expression is a postfix operator).
Its solution is give up on finding a second argument if there is an interceding new line.

scala - error: ')' expected but '(' found

I'm new to Scala and I cannot find out what is causing this error, I have searched similar topics but unfortunately, none of them worked for me. I've got a simple code to find the line from some README.md file with the most words in it. The code I wrote is:
val readme = sc.textFile("/PATH/TO/README.md")
readme.map(lambda line :len(line.split())).reduce(lambda a, b: a if (a > b) else b)
and the error is:
Name: Compile Error
Message: <console>:1: error: ')' expected but '(' found.
readme.map(lambda line :len(line.split()) ).reduce( lambda a, b: a
if (a > b) else b ) ^
<console>:1: error: ';' expected but ')' found.
readme.map(lambda line :len(line.split()) ).reduce( lambda a, b: a
if (a > b) else b ) ^
Your code isn't valid Scala.
I think what you might be trying to do is to determine the largest number of words on a single line in a README file using Spark. Is that right? If so, then you likely want something like this:
val readme = sc.textFile("/PATH/TO/README.md")
readme.map(_.split(' ').length).reduce(Math.max)
That last line uses some argument abbreviations. This alternative version is equivalent, but a little more explicit:
readme.map(line => line.split(' ').length).reduce((a, b) => Math.max(a, b))
The map function converts an RDD of Strings (each line in the file) into an RDD of Ints (the number of words on a single line, delimited - in this particular case - by spaces). The reduce function then returns the largest value of its two arguments - which will ultimately result in a single Int value representing the largest number of elements on a single line of the file.
After re-reading your question, it seems that you might want to know the line with the most words, rather than how many words are present. That's a little trickier, but this should do the trick:
readme.map(line => (line.split(' ').length, line)).reduce((a, b) => if(a._1 > b._1) a else b)._2
Now map creates an RDD of a tuple of (Int, String), where the first value is the number of words on the line, and the second is the line itself. reduce then retains whichever of its two tuple arguments has the larger integer value (._1 refers to the first element of the tuple). Since the result is a tuple, we then use ._2 to retrieve the corresponding line (the second element of the tuple).
I'd recommend you read a good book on Scala, such as Programming in Scala, 3rd Edition, by Odersky, Spoon & Venners. There's also some tutorials and an overview of the language on the main Scala language site. Coursera also has some free Scala training courses that you might want to sign up for.

How do I write a perl6 macro to enquote text?

I'm looking to create a macro in P6 which converts its argument to a string.
Here's my macro:
macro tfilter($expr) {
quasi {
my $str = Q ({{{$expr}}});
filter-sub $str;
};
}
And here is how I call it:
my #some = tfilter(age < 50);
However, when I run the program, I obtain the error:
Unable to parse expression in quote words; couldn't find final '>'
How do I fix this?
Your use case, converting some code to a string via a macro, is very reasonable. There isn't an established API for this yet (even in my head), although I have come across and thought about the same use case. It would be nice in cases such as:
assert a ** 2 + b ** 2 == c ** 2;
This assert statement macro could evaluate its expression, and if it fails, it could print it out. Printing it out requires stringifying it. (In fact, in this case, having file-and-line information would be a nice touch also.)
(Edit: 007 is a language laboratory to flesh out macros in Perl 6.)
Right now in 007 if you stringify a Q object (an AST), you get a condensed object representation of the AST itself, not the code it represents:
$ bin/007 -e='say(~quasi { 2 + 2 })'
Q::Infix::Addition {
identifier: Q::Identifier "infix:+",
lhs: Q::Literal::Int 2,
rhs: Q::Literal::Int 2
}
This is potentially more meaningful and immediate than outputting source code. Consider also the fact that it's possible to build ASTs that were never source code in the first place. (And people are expected to do this. And to mix such "synthetic Qtrees" with natural ones from programs.)
So maybe what we're looking at is a property on Q nodes called .source or something. Then we'd be able to do this:
$ bin/007 -e='say((quasi { 2 + 2 }).source)'
2 + 2
(Note: doesn't work yet.)
It's an interesting question what .source ought to output for synthetic Qtrees. Should it throw an exception? Or just output <black box source>? Or do a best-effort attempt to turn itself into stringified source?
Coming back to your original code, this line fascinates me:
my $str = Q ({{{$expr}}});
It's actually a really cogent attempt to express what you want to do (turn an AST into its string representation). But I doubt it'll ever work as-is. In the end, it's still kind of based on a source-code-as-strings kind of thinking à la C. The fundamental issue with it is that the place where you put your {{{$expr}}} (inside of a string quote environment) is not a place where an expression AST is able to go. From an AST node type perspective, it doesn't typecheck because expressions are not a subtype of quote environments.
Hope that helps!
(PS: Taking a step back, I think you're doing yourself a disservice by making filter-sub accept a string argument. What will you do with the string inside of this function? Parse it for information? In that case you'd be better off analyzing the AST, not the string.)
(PPS: Moritz++ on #perl6 points out that there's an unrelated syntax error in age < 50 that needs to be addressed. Perl 6 is picky about things being defined before they are used; macros do not change this equation much. Therefore, the Perl 6 parser is going to assume that age is a function you haven't declared yet. Then it's going to consider the < an opening quote character. Eventually it'll be disappointed that there's no >. Again, macros don't rescue you from needing to declare your variables up-front. (Though see #159 for further discussion.))

What is the meaning of colon, underscore and star in lift's SiteMap(entries:_*)?

I'm learning Scala and lift at the same time and I got stuck on understanding the syntax used to inintialize the SiteMap in the Boot.scala:
val entries = Menu(Loc("Home", "/", "Home")) ::
Menu(Loc("Foo", "/badger", "Foo")) ::
Menu(Loc("Directory Foo", "/something/foo", "Directory Foo")) :: Nil
LiftRules.setSiteMap(SiteMap(entries:_*))
What exactly is the meaning of the SiteMap parameter?
I see that the value entries is a list of Menu. What is the colon, underscore, star?
At first I thought it is a method on the List, but I am unable to find such definition...
OK, after my colleague mentioned to me, that he encountered this secret incantation in the Programming in Scala book, I did a search in my copy and found it described in Section 8.8 Repeated parameters. (Though you need to search with space between the colon and underscore :-/ ) There is a one sentence to explain it as:
... append the array argument with a colon and an _* symbol, like this:
scala> echo(arr: _*)
This notation tells the compiler to pass each element of arr as its own argument to echo, rather than all of it as a single argument.
I find the description offered here more helpful.
So x: _* is like a type declaration that tells the compiler to treat x as repeated parameter (aka variable-length argument list — vararg).