background preloader

Roundup: Scala for Java Refugees

Roundup: Scala for Java Refugees
13 Feb 2008 To be honest, I’m somewhat kicking myself for writing this post. As I’ve said many times: roundup posts are for people who are too lazy to write real content. I can’t tell you how many blogs I’ve come across which have a roundup-to-post ratio of easily 3:1. Meta-roundups aside, I decided (after much deliberation) that a single post linking to all six parts of the series would be useful to one or two people. Of course it’s always possible that you subscribe to my way of looking at things. Part 1: main(String[]) Introductory article giving motivation for learning Scala and some first steps to “get your feet wet” in the language. Part 2: Basic OOP Looking at Scala’s syntax in a little more detail. Part 3: Methods and Statics Scala’s method syntax is far too powerful to cover in a single post. Part 4: Pattern Matching and Exceptions Pattern matching is one of the most useful constructs in the entire language. Part 5: Traits and Types Part 6: Getting Over Java

Why Scala? Before answering the question of "Why Scala?", we first need to answer the question "what is Scala?" From the Scala website, the following overview can be found: Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. For some developers, these incentives will be enough to lure you away from Java into the Scala world. So, once again, "why Scala?" In a post titled "Scala: The best of both Ruby and Java", Ian describes that it might not be a choice between Java and Scala, but instead the choice to use a combination of Java and Scala as an alternative to other language choices such as Ruby: Many programmers love Ruby, they just can’t get enough of it. To further show the reduction of code in a less trival example, Ted Neward explores the differences between a class developed in Java, C#, Visual Basic, Ruby and Scala in his blog posting Scala pt 2: Brevity. Continuing on, Ian notes that:

The Scala Programming Language Scala as the long term replacement for java/javac? Don't get me wrong - I've written tons of Java over the last decade or so & think its been a great evolutionary step from C++ and Smalltalk (lots of other languages have helped too like JavaScript, Ruby, Groovy, Python etc). However I've long wanted a long term replacement to javac. I even created a language to scratch this itch. Java is a surprisingly complex language (the spec is 600 pages and does anyone really grok generics in Java?), with its autoboxing (and lovely NPE's hiding in there), primitive types, icky arrays which are not collections & general lack of polymorphism across strings/text/buffers/collections/arrays along with extremely verbose syntax for working with any kind of data structure & bean properties and still no closures (even in JDK7) which leads to tons of icky try/catch/finally crapola unless you use frameworks with new custom APIs & yet more complexity. So whats gonna be the long term replacement for javac? So why Scala? e.g. in Java List<String><String> in Scala

Thinking in Scala vs Erlang : Caoyuan&#039;s Blog Keeping Erlang in mind, I've coded two months in Scala, I'm thinking something called "Scala vs Erlang", I wrote some benchmark code to prove me (the code and result may be available someday), and I'd like to do some gradually summary on it in practical aspect. These opinions may be or not be correct currently due to lacking of deep experience and understanding, but, anyway, I need to record them now and correct myself with more experiences and understanding got on both Scala and Erlang. Part I. List comprehension ¶ Erlang: Lst = [1,2,3,4],[X + 1 || X <- Lst],lists:map(fun(X) -> X + 1 end, Lst) Erlang Scala: val lst = List(1,2,3,4) for (x <- lst) yield x + 1 lst.map{x => x + 1} lst.map{_ + 1} // or place holder Scala Pattern match ¶ case X of {A, B} when is_integer(A), A > 1 -> ok; _ -> error end, {ok, [{A, B} = H|T]} = my_function(X) List, Tuple, Array, Map, Binary, Bit ¶ Lst = [1, 2, 3] %% List [0 | Lst] %% List concat {1, 2, 3} %% Tuple <<1, 2, “abc”>> %% Binary %% no Array, Map syntax Scala I:

First Steps to Scala ScalazineFirst Steps to Scalaby Bill Venners, Martin Odersky, and Lex SpoonMay 9, 2007 Summary In this article, you'll follow twelve steps that are designed to help you understand and gain some basic skills in the Scala programming language. Scala is a statically typed, object-oriented programming language that blends imperative and functional programming styles. Scala was developed starting in 2003 by Martin Odersky's group at EPFL, Lausanne, Switzerland. One reason you might want to use Scala is that it allows you to increase your productivity compared to Java while leveraging JVM execution speed, your existing investments in Java code, knowledge, and the vast array of APIs available for the JVM. In Italian, Scala means staircase. To run the examples in this article, you should download Scala from the Scala Downloads page. The easiest way to get started with Scala is by using the Scala interpreter, which is an interactive “shell” for writing Scala expressions and programs. scala> 1 + 2

Can Your Programming Language Do This? by Joel Spolsky Tuesday, August 01, 2006 One day, you're browsing through your code, and you notice two big blocks that look almost exactly the same. // A trivial example: alert("I'd like some Spaghetti!") These examples happen to be in JavaScript, but even if you don't know JavaScript, you should be able to follow along. The repeated code looks wrong, of course, so you create a function: function SwedishChef( food ) { alert("I'd like some " + food + "!") OK, it's a trivial example, but you can imagine a more substantial example. Now you notice two other blocks of code which look almost the same, except that one of them keeps calling this function called BoomBoom and the other one keeps calling this function called PutInPot. alert("get the lobster"); PutInPot("lobster"); PutInPot("water"); alert("get the chicken"); BoomBoom("chicken"); BoomBoom("coconut"); Now you need a way to pass an argument to the function which itself is a function. Look! Can your language do this? Jeez, that is handy.

Scala Syntax Primer Scala runs on the JVM and can directly call and be called from Java, but source compatibility was not a goal. Scala has a lot of capabilities not in Java, and to help those new features work more nicely, there are a number of differences between Java and Scala syntax that can make reading Scala code a bit of a challenge for Java programmers when first encountering Scala. This primer attempts to explain those differences. This primer is not intended to be a complete tutorial on Scala, rather it is more of a syntax reference. Most of these syntax differences can be explained by two of Scala's major goals: Minimize verbosity. (0/:list)(_+_) Scala is an integrated object/functional language. You can run the Scala interpreter and type in these examples to get a better feel for how these rules work. Contents Basics Scala classes do not need to go into files that match the class name, as they do in Java. Keywords Symbols and Literals Expressions Case and Patterns For Expressions Arrays Tuples Classes

Comparison of Hash Table Libraries « Attractive Chaos August 28, 2008 by attractivechaos As a Perl programmer, I enjoy a lot using hash tables. I keep this habit in C/C++ programming. Then what C/C++ hash libraries are available? How are they compared to each other? In this post, I will give a brief review of hash libraries and present a small benchmark showing their practical performance. Hash table libraries In C++, the most widely used hash table implementation is hash_map/set in SGI STL, which is part of the GCC compiler. In contrast, there are few good C libraries around. Design of the benchmark The benchmark is comprised of two experiments. The second experiment is designed by Craig Silverstein, the author of sparsehash. Results The following table gives the results in the first experiment: Notes: Please be aware that changing the size of input data may change the ranking of speed and memory. And here is the result of the second experiment: CPU time is measured in nanosecond for each operation. Discussions Speed and memory. Update Like this:

A Taste of 2.8: The Interactive Interpreter (REPL) The Scala Interpreter (often called a REPL for Read-Evaluate-Print Loop) sits in an unusual design space - an interactive interpreter for a statically typed language straddles two worlds which historically have been distinct. In version 2.8 the REPL further exploits the unique possibilities. Package and Class Completion On startup, the REPL analyzes your classpath and creates a database of every visible package and path. scala> scala.co<tab> collection compat concurrent scala> org.w3c.dom.DOMI<tab> DOMImplementation DOMImplementationList DOMImplementationSourcescala> org.w3c.dom.DOMImplementation Member Completion Both static and instance methods of objects are also available. scala> val x = "abc" x: java.lang.String = abc scala> x.re<tab> regionMatches replace replaceAll replaceFirst scala> java.lang.String.c<tab> scala> java.lang.String.copyValueOf And because this is all accomplished on the fly via reflection, even anonymous classes you've only just defined are equally accessible.

Excellent Overview of Functional Programming 14 Feb 2008 I just ran into an article on DZone that totally threw me off my chair in terms of content. It’s titled (ambitiously enough) “Functional Programming For the Rest of Us“. Basically the article attempts to explain many of the common FP techniques in terms that imperative programmers can understand. More importantly, it motivates these explanations with a long and rambling set of real-world reasons. It’s worth noting that the author claims to be presenting his explanations in Java, but is in fact devising an extension of Java to represent FP constructs more concisely. The really interesting bit is how the author motivates FP through a combination of real-world examples and lengthy reasoning. So grab yourself a cup of coffee and a box of donuts (it’ll take you about that long to finish the article), and slog your way through.

Ruby over Scala As promised, here is where I'll be maintaining the things I like about Ruby better than Scala. In general, I do think I prefer programming in Scala, but certainly some of the things I can do in Ruby are much easier. If you're looking the other post, its here: Scala over Ruby. This list is my no means complete and as with the other list, I'll be appending to it here as I learn more. Pimp My Library I'll dive into some general theory about this first, but for those who just want to see the code, just scroll down. There's been so many times when I've needed to add methods to classes, for good reasons. Let's use an example in Scala. def compact[T]( list: List[T] ) = l.filter( _ ! But as I just said, calling operations on your data consistently is important for readability. One solution is to simply add that method to the class you're operating on. class Compactable[T](l: List[T]){ def compact = l.filter( _ ! implicit def compactableList[T]( l: List[T] ) = new Compactable(l) Classes are Objects

Scala 2.8 Collections API September 7, 2010 In the eyes of many, the new collections framework is the most significant change in Scala 2.8. Scala had collections before (and in fact the new framework is largely compatible with them). But it's only 2.8 that provides a common, uniform, and all-encompassing framework for collection types. Even though the additions to collections are subtle at first glance, the changes they can provoke in your programming style can be profound. In fact, quite often it's as if you work on a higher-level with the basic building blocks of a program being whole collections instead of their elements. Easy to use: A small vocabulary of 20-50 methods is enough to solve most collection problems in a couple of operations. Concise: You can achieve with a single word what used to take one or several loops. Safe: This one has to be experienced to sink in. Fast: Collection operations are tuned and optimized in the libraries. Universal: Example: Next:

Introduction Haskell is a computer programming language. In particular, it is a polymorphically statically typed, lazy, purely functional language, quite different from most other programming languages. The language is named for Haskell Brooks Curry, whose work in mathematical logic serves as a foundation for functional languages. Haskell is based on the lambda calculus, hence the lambda we use as a logo. 1 Why use Haskell? Writing large software systems that work is difficult and expensive. WOW! Even if you are not in a position to use Haskell in your programming projects, learning Haskell can make you a better programmer in any language. I learned Haskell a couple of years ago, having previously programmed in Python and (many) other languages. Haskell offers you: Substantially increased programmer productivity (Ericsson measured an improvement factor of between 9 and 25 using Erlang, a functional programming language similar to Haskell, in one set of experiments on telephony software). 3.4 Brevity

scheme-vs-common-lisp Copied from a comp.lang.lisp post by Ray Dillinger. Also see PPR:LispSchemeDifferences ,common-lisp. What Common Lisp has got: What Scheme has got: Much better developed standard SLIB + SRFI's + a hundred little libraries libs that each do things differently and aren't very standardized. (Arguably Scheme is the place where new ideas fight for mindshare and prove themselves - but the fights and the multiplicity of contenders commits most code to one idea or another and limits the code's interoperability, longevity, and/or portability.) category-learning-scheme

Related: