Effective Scala
twitter.github.io
twitter.github.io
I am currently porting a Clojure library of mine to Scala, and it is about 10% less code, and obviously more robust because of static type checking.
Scala.js: https://github.com/lampepfl/scala-js
In short: more robust
$ cat NotTypesafe.scala
object NotTypesafe {
def main(args: Array[String]) {
println("5".asInstanceOf[Int])
}
}
$ scalac NotTypesafe.scala
$ scala NotTypesafe
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
http://en.wikipedia.org/wiki/Type_safety (defn completion-items [grammar doc items-bin-index completed-bin-index items nonterminal value]
(loop [items items
completed '()]
(if-let [[^Item item previous-value] (first items)]
(let [alpha (expected-symbol grammar item)
dot (.dot item)]
(if (and alpha (= nonterminal alpha))
(let [rule-nonterminal (.nonterminal item)
ruleindex (.ruleindex item)
origin (.origin item)
value' (gen-nextvalue grammar doc origin items-bin-index completed-bin-index
rule-nonterminal ruleindex dot
previous-value value)]
(if (nil? value')
(recur (next items) completed)
(let [item' (->Item rule-nonterminal ruleindex (+ dot 1) origin)]
(recur (next items) (cons-item-value completed item' value')))))
(recur (next items) completed)))
(apply hash-map completed))))
--------------------------------------------------------
def complete_items(completed_binindex : Int, bin : ItemBin, nonterminal : Nonterminal, value : Value) : MoreItems = {
var completed_items : List[(Item, IntermediateValue)] = List()
for ((item, v) <- bin.items) {
val s = expectedSymbol(item)
if (s == Some (nonterminal)) {
grammar.nextValue(document, item.origin, bin.binindex, completed_binindex, nonterminal,
item.ruleindex, item.dot, v, value) match
{
case None =>
case Some(nextvalue) =>
completed_items = (item.inc -> nextvalue) ::
completed_items
}
}
}
completed_items
}1) Unnecessary type hint
2) No use of destructuring or field lookup by keyword
3) Alteration of record objects with positional constructors instead of update-in
4) Explicit loop with previous item instead of reduce over (partition 2 1 items)
5) Way too many parameters
6) Apply hash-map instead of into
7) (+ ... 1) instead of inc
8) Weird gen-nextvalue auxiliary function instead of a lazy sequence
I could keep going...
(defn completion-items [items options]
(->> (for [[item v] items]
(when-let [nonterminal (expected-symbol item options)]
(when-let [next-value (gen-next-value v options)]
[(update-in item [:dot] inc) next-value])))
(remove nil?)
(into {})))By the way, gen-nextvalue is a protocol function.
No, not really. That has only been my experience when interoperating with Java libraries. Protocol dispatch has inline call caches, which are almost as fast as normal java interface dispatch.
> that is the problem with a language feature which is not a compiler feature as well
You could also say "that is the problem with type system features which are not virtual machine features as well". There is lots of erased information in the Scala type system that could be used for optimizations, but the VM can't make much use of that.
Scala's type system does 3 things:
1) Enable type-related optimizations
2) Ensure internal consistency (ie prevent errors)
3) Enhance expressivity through logic solver search
Clojure's type hints provide just enough type system to trigger host optimizations, where as core.typed is for finding and preventing bugs. I consider the implicitness of #3 to be an anti-feature.
idiomatic == I am doing what I am told to do without understanding why it sometimes makes sense, and sometimes doesn't, and sometimes just doesn't matter.
def complete_items(...) = bin.items.flatMap((item, v) =>
expectedSymbol(item).map(nonterminal =>
grammar.nextValue(document, item.origin, bin.binindex, completed_binindex, nonterminal, item.ruleindex, item.dot, v, value)
.map(nextvalue => (item.inc -> nextvalue)
)
)If you're going to do a lot of appending, might I suggest a ListBuffer or a Vector?
TraversableLike, and FilterMonadic will both size up the resulting return value based upon the length of what's passed to it. You'll get a List of N items, and the call to flatMap will also traverse the list to remove/flatten the Options. Items will then get dropped in the List. You're looking at one or two collectable objects every time you run through that method, as opposed to bin.items.length collectable objects in your original code.
Look at it this way-- what happens if bin.items is a List() of 10M objects? completed_items can be replaced up to 10M times. The .flatMap creates one collection of 10M length, removes the None objects, and returns the resulting List.
def complete_items(completed_binindex: Int, bin: ItemBin, nonterminal: Nonterminal, value: Value): MoreItems = {
for {
(item, v) <- bin.items
_ <- expectedSymbol(item)
nextValue <- grammar.nextValue(document, item.origin, bin.binindex, completed_binindex,
nonterminal,item.ruleindex, item.dot, v, value)
} yield {
item.inc -> nextvalue
}Programming in Clojure I miss the following features from Scala most:
a) Pattern matching
b) Having machine-checked documentation (aka type system), traits.
c) A proper documentation generation tool. The Clojure one doesn't do protocols properly, although protocols are the only real way in Clojure to have something akin' to interfaces and Scala traits.
a) https://github.com/clojure/core.match
b1) https://github.com/clojure/core.typed
b2) I agree that Clojure's facilities for mixins is under-utilized and that it lacks a proper facility for delegation (ie implicit conversions in Scala), but see (doc extend) for how awesome "traits as data" can be. Here's an example: https://github.com/stuartsierra/clojure.walk2/blob/2250e04c7...
c1) I hate generated documentation, but I understand why it's necessary for Scala. When I did some scala programming, I was so pleased with ScalaDoc, since it really helps you navigate that complex scala.collections hierarchy. Feels like having a pretty decent substitute to a good IDE. In Clojure, I don't feel the need nearly as much... Also, I quite like reflective documentation with the doc macro.
c2) Already covered interfaces/traits in b2
/** My comment
* Next Line
*/
which is pretty ugly, but it is /** My comment
* Next Line
*/
which looks much better. :-)I think Scala.js is going to be huge. Just alone for that I would choose Scala over Go.
But I certainly do not believe that Scala.js has a reasonable chance of having an impact alike GWT or such; maybe it can get close to (ruby) Opal or consorts, though. The main selling point of Scala still is Akka, and, at least in the web-dev world, the Play framework, I guess.
I am not using Akka, I am not using Play, I only use Scala because it is currently the language I can express my thoughts in the most elegant way, together with its industrial strength ecco system AND BECAUSE IT COMPILES TO JAVASCRIPT, TOO!!!
GWT never convinced me, Java is less productive than Javascript, so what is the point (except for legacy Java programmers ...).
Scalatra - Scala's Sinatra
Blue Eyes - appears defunct but good example of pure asynchronous framework
Lift - strong built-in security, Netty integration wip.
Probably a couple more I'm forgetting.
But ask yourself this: do you work in a team or alone? One of the first sentences is:
"While highly effective, Scala is also a large language, and our experiences have taught us to practice great care in its application."
And thats the biggest issue - Scala is a bit like the JVMs C++, you need capable programmers in order to not fuck it up, because it contains every paradigm ever invented.
Go on the other hand is much simpler, and I like it for that - there is great value in simplicity.
Also, when speaking of simplicity, I like languages with conceptual elegance. Scheme is simple too and that's a rather interesting example. You see, Scheme is homoiconic and has macros and continuations, a combination so powerful that you can easily build on top and efficiently use any pattern or paradigm under the sun. Also, being a Lisp, most builtins can be reimplemented in Scheme.
Now that's simple. What you're describing is actually easyness which is a very different notion. The main difference is that easiness is relative and depends on someone's own biases or limitations. The problem of course is that easy can overnight turn into hard.
Ever tried doing FP in Go? Ever thought about implementing your own data-structures? Try it.
I have written both Scala and C++ at my day jobs and I would say that Scala certainly does generally remind me of C++ and specifically in its proliferation of language features. I also know of several others with similar experience and opinion on this matter.
Also, I completely agree with the rest of your original post (the parts RE: Scheme, Go, & simplicity).
Sometimes the result is Scala source files that almost appear to be written in different languages, or lots of little libraries each with their own wacky DSLs that require a major investment of time to comprehend just to accomplish something that should be trivial.
These sorts of abuses you really don't see in Clojure even though it's just as possible in that language. Of course this is all based just on my experience, YMMV.
But even Clojure is syntactically heavy compared to Racket or CL. But with good reason.
A powerful and expressive language takes effort, possibly even years, to become expert in. I'm not sure that making trivial things trivial is part of the plan. There are more appropriate languages for that.
Most of the cruft in Scala is due to its support of O-O and its attempt to modernize it. Similarly, C++ is a superset of C rather than a complete break from it (and often, in the field, you find people using it as if it were 'C with classes').
Also, the O-O side of Scheme is certainly more powerful than F#'s O-O side; however, overall F# is at least as powerful of a language (and yet it's also much cleaner/internally consistent).
[Also, it takes only one counter-example to disprove 'all those who say that Scala resembles C++ have never worked with either' (which was my original intent here)].
My team has just the opposite experience. Scala offers a lot of structure and discipline that you can take advantage of without being an expert, and it is a short time to ramp up to idiomatic usage relative to other languages. In fact, this is one of its benefits. By following some fairly simple guidelines, you can avoid making a mess. This has not been my observation with imperative programmers picking up a new imperative language.
Because of the easy-to-achieve discipline, Scala is ideal for teams in my opinion.
-You think a fusion of OO and functional programming is the way of the future
-Runtime tooling and advanced instrumentation support matter to you
-You like having first-class IDE support
-You want to work for the likes of Twitter/Foursquare/LinkedIn/Amazon
-Having tons of mature Java libraries available matters to you.
-You don't mind investing time to learn the language
Pick Go if: -Memory footprint matter to you (and you don't want to pick C)
-Startup time matters to you (and you don't want to pick C)
-You don't want to spend much time learning the language
-You like C-style error handling and aren't expecting something as expressive as a python or a ruby.
-You don't mind limited IDE support
-You want every post of yours to be voted up on HN regardless of contentPick Scala if:
-You find value in strong static assurances.
-You find value in generics.
-You want to learn functional programming, not 'functional' programming (and you should).
-You value succinctness.
Pick Go if: -Compile times matter (of course it does).
-You find value in easier deployments (at the cost of potentially more deployments).
-You don't want to learn D ;)Pick Scala if: all other things
Is there any clear evidence of better memory management in Go comparing to JVM?
Scala is to Ruby what Go is to Python.
Python:C++::Go:Scala
Like Go, they make the tradeoff not to have C++ generics for faster and smaller compiles.
https://gist.github.com/jroper/6374383
If you dig thru the internals list, there are a number of fronts they're working on to produce fewer short lived intermediate objects, parallelize builds etc
https://groups.google.com/forum/?_escaped_fragment_=forum/sc...