because Hindley-Milner rocks
Python is a wonderful language. I use it for scripting all the time. Hell, I use it for prototyping things too! I love that REPL. Using it I’ve had many “Eureka!” moments. I think the biggest moment was discovering the true power of for comprehensions followed up by generators or as I like to call them, lazy eval for comprehensions. Scala has for comprehensions but they’ve also got some nifty built in functionality that avoids the need to write for comprehensions.
tupleList = [ (index,item) for (index,item) in enumerate( myList ) ] tupleList = list( enumerate( myList ) ) #Rob Smallshire's much better version
It’s short enough to be a one liner. Here’s what it looks like in Scala:
val tupleList = myList zipWithIndex
Not only is that less complicated to read but it’s also much more descriptive with it’s intent. As an added bonus it doesn’t force the programmer to repeat themselves, a la (index,item) twice and After Rob pointed out in the comments below a much more concise and to the point version I’ve had to retract what I said previously. I’ll leave it up for everyone to see since I’m not right all the time. However, I will continue to say that zipWithIndex probably won’t show up in some “hidden feature” posting about Scala. Better yet, tell me which one you’d rather type when When converting between a list and a map:
myMap = dict( [ (index,item) for (index,item) in enumerate( myList ) ] ) myMap = dict( enumerate( myList ) ) #Rob Smallshire's version
or and the Scala version:
val myMap = Map( myList zipWithIndex: _* )
I’m not saying Scala is a better language than Python, in many ways it’s not. Both have their uses. Besides, I’d actually use a generator (Python’s enumerate is a generator, thanks Rob) instead of the for comprehension in Python and a Stream in Scala. Why? They don’t create a temporary list which is much more efficient. I’ll have to revisit this post again some day soon.
If you’re wondering, I’m using Eclipse with the updated Scala 2.7.7 plug-in. It’s not as snazzy as the NetBeans but I do like the coloring scheme more.