Scala is Not a Functional Programming Language May 14, 2009 | 06:19 pm

Having now worked a fair amount with Scala, I can now unequivocally make this assertion:

Scala is not a functional programming language. It is a statically typed object oriented language with closures.

So, I’d appreciate it if people would stop the bogus sales pitch.

To understand the distinction, take a look at this surprisingly interesting troll from Jon Harrop on the Scala mailing list. In that thread, Martin O. puts out a challenge, and claimed that OO solutions were the only “clean” one. One clean SML solution later, there was some refinement of the claim, that being that OO solutions were the cleanest ones when you had to replace your application’s core data structure many times. Ultimately, the conversation got bogged down in pedantic points about the particular challenge, but it was fascinating when it lasted.

The key interesting point I walked away with was this quote from Martin O.:

An implementation of an abstract {def, val, type} can refer to other members of its superclass. But an argument to a higher order method or functor cannot refer to the result of the application. So open recursion with abstraction is supported in OOP but it requires elaborate and rather tedious boilerplate in FP (such as the encodings of classes in TAPL).

Now, this statement is kinda silly — as defined in Pierce, “open recursion” is an implicitly OO concept, so of course the FP languages have pain when you try to code them in a different paradigm. The question is whether that technique is necessary or even worthwhile in functional programming: does functional programming have an easy way to solve the same problems, or is it limited because it cannot pull this stunt?

So, when considering whether Scala is a functional programming language, let’s ask ourselves: how does Scala solve problems? Brian Hurt is fond of saying that when it comes to the nature of the language, it’s not about what the language makes possible, it’s what the language makes easy*. What does Scala make easy?

* Notably Martin O. seems to disagree: “The first thing we cared about was to have as clean an integration of functional and object-oriented programming as possible. We wanted to have first-class functions in there, function literals, closures. We also wanted to have the other attributes of functional programming, such as types, generics, pattern matching. And we wanted to integrate the functional and object-oriented parts in a cleaner way than what we were able to achieve before with the Pizza language. That was something we deeply cared about from the start. Later on, we discovered that this was actually very easy, because functional languages have a fixed set of features. ” (cite) — so, according to that thinking, if you hit the items on the check list, you’re a functional programming language. More on this later.

Let’s start with the basics: in a functional programming language, you program functions. That is, the solution is to encode the problem as function application. In OCaml, we define a function like this:

let f x = x + 1;;

In Scala, though, we define the function somewhat differently:

object SomeHolderObject {
  val f(x:int):int = { x + 1 }
}

In OCaml, functions are defined directly — in Scala, we have to give an objective context to the function. Using the “object” keyword gives us a singleton object that we act against, but that’s no more functional an approach than the static context used by Java. So, at its fundamental organizational structure, Scala betrays its purportedly functional nature to be more object oriented.

Now, let’s consider where the abstraction lies in Scala. In Scala, the key way to abstract things is to implement partial contracts, either in the forms of interfaces or traits. Traits are the implementation of open recursion in Scala, which (despite its name) is precisely an OO feature! So now we’ve got Scala’s basic organization being objective, and Scala’s source of abstraction power being objective. 0 for 2.


For the shut-out, let’s see in Scala makes functional programming easy. Let’s start with my favorite functional language stunt: currying.

OCaml, you’re up to bat first.

let x a b = a + b;;
let y = x 1;;
y 2;; (* 3 *)

Not too shabby. Scala, show your stuff!

def x(a:Int, b:Int) = a + b 
def y = x(1)
/*  ERK!   FAIL!
<console>:5: error: wrong number of arguments for method x: (Int,Int)Int
       def y = x(1)
               ^
*/

Want to try that again?

def x(a:Int, b:Int) = a + b 
def y = Function.curried(x _)(1)
y(2)  // 3

So, currying is possible, but not exactly easy (or pretty) compared to a real functional language. Okay, well, that’s fine. A bit of ugliness is minor: let’s try something more basic and fundamental to the algebraic functional programming paradigm.

What about Algebraic Data Types, common to functional languages — including my beloved OCaml variant types? They provide a key power behind pattern matching and static typing in OCaml/F# and Haskell — how does Scala fair?

Well, in OCaml, I’d write this:

type robert = Foo of int | Bar of string | Baz;;

In Scala, we get this:

sealed abstract class Robert;
sealed case class Foo(value:Int) extends Robert;
sealed case class Bar(value:String) extends Robert;
sealed case class Baz extends Robert;

Oh, ugh. For a while there, I thought that noise was kinda-sorta justified because it allowed for case class inheritance — but that feature’s being driven from the codebase (more on that here). So it’s just plain noisy compared to the OCaml version.

This blog post could go on like this for a while, but I’ll invoke a mercy rule and simply say: Is Scala making functional programming idioms easy? No. 0 for 3.

So, what lead to the claim that Scala was a functional language is the first place? First-level functions? Perl, Ruby, and Groovy have those, and they’re not being called “functional languages”. Statically typed closures? C#. Matching? Easy to do in an OO style (cite), and largely wasted without easy algebraic data types. A penchant for immutability? That’s a good start, but is far from sufficient to make it a functional programming language.

No, Scala is not a functional language, because it doesn’t make functional programming easy. It makes it possible, and so the language certainly has functional accents, but Scala is not a functional language at its core. OCaml makes object oriented programming possible, and so the language has object accents, but OCaml is not an object-oriented language at its core. And that’s okay — but let’s call a spade a spade.

And don’t get me wrong: as a JVM language, Scala is a huge step forward. C# has so far outstripped Java as a language that it’s downright embarrassing, and Scala leapfrogs ahead of C# to put the JVM back in the lead. But Scala is first and foremost an object oriented language, so can we stop calling it a “functional programming language”? It’s deceptive, and it’s degrading what it means to be a functional programming language.

  • http://www.smokejumperit.com Robert Fischer

    @Willis Blackburn

    I’m right there with you: read the first couple of paragraphs and the last couple of paragraphs of the original post again.

    All I ask throughout this post is that we stop referring to Scala as a “functional programming language”, or giving it credit for being particularly “mathematical”. My concern is that people won’t learn real functional programming languages because they think they already know one — Scala! Scala isn’t a functional programming language, and doesn’t encourage the same kind of programming paradigm that Haskell/OCaml does, which revolutionized the way I wrote code: including Java code!

  • http://rgzblog.blogspot.com rgz

    If Scala supports referential transparency, in other words if f(x) == f(x) always, it’s functional enough to me. So Scala lets you define functions outside objects and provides syntactic support for curring so what’s left?

    That it doesn’t encourage algebraic types?

    That’s not required for functional programming as Erlang shows.

    I actually like this kind of articles because I learn a lot. So thanks for writing it even if you wouldn’t admit you are wrong if your life depended upon it.

  • http://www.smokejumperit.com Robert Fischer

    @rgz

    You’re welcome. And I’m more than happy to admit I’m wrong — I’m not one to cling to stances very long, and I’m not arguing for the sake of being argumentative here. While this conversation has revealed a lot about what I didn’t understand about Scala, and while I would write a different (and lengthier) blog post if I had it to do all over again, my core assertion is not something anyone’s particularly disagreed with.

    Unless I’ve missed something, everyone seems to agree that Scala isn’t a functional language, it’s an OO language hybridized with functional programming. And everyone seems to agree that functional programming isn’t exactly super easy in Scala (esp. when compared to languages like OCaml/Haskell). Therefore, people seem to be agreeing that OO solutions are more natural in Scala than declarative ones, especially when designing “in the large”. If I did miss something, I’d like to know what assertion out of that list people are arguing with: a direct quote and a direct rebuttal would be nice.

    AFAICT, the arguments mainly seem to be around:
    1) whether it’s fair to make any declaration like “X is not a Y programming language” without strict definitions of “Y programming language”
    2) whether my examples were the best possible ones (or, less charitably, useful/relevant at all)
    3) whether it’s a waste of time to write “blog posts like this”, and whether I owe people minutes of their life back.

    All of which I’m willing to discuss, and each of which I certainly understand.

  • Pingback: Web Dev Geekly #14 | Enfranchised Mind

  • http://www.smokejumperit.com Robert Fischer

    I love this pingback:

    Finally read this:
    1. It wasn’t as much a pissing contest as I thought it would be. I learned something from both sides
    2. Provocative titles get traffic.

  • Pingback: Enfranchised Mind » Anything Anyone Wants to Hear from Me?

  • Pingback: Enfranchised Mind » What is a functional programming language?

  • Pingback: Fragments forthcoming « Doug Milam

  • Yves Bossel

    Take the best academic programmers and you will eventually get a very good program (and tons of academic and very clever descriptions about its wonderful advantages).

    To make a real life code base, say a bank’s 10000 classes or more, take lots of ignorant code-typers, a few average engineers, some of them clever. The result is very much ugly/horrible/terrific code, academically unmaintainble, and very few clever ideas always half-way.

    The real life code base just works (thousands of happy and unhappy customers).

    The real point about real life programming is that very different people can join around a programming language/patterns/idioms/frameworks/versions and they can interpret partially each other’s code, and expand it.

    Experimented people learn to guide less skilled coders in order to improve the code base. Both learn, both grow up.

    Language purity is just as sterile as trying to have everybody think and act the same way.

    The PhD professor writing a beautiful higher-order function is right as long as his findings are useful to someone else.
    The stupid coder who programs using Ctrl-Tab code-completion is also right as long as the bank’s customers can get the bank’s services.

    So your arguments about being functional or not are futile.

    In everyday world you do not choose the people you work with and you do not choose the existing code base. You enter into a flow of always evolving code and people, and you have to help others to evolve from the existing code base in a way THEY can make sense of it.

    You could help functional language ignorants like me explaining me what is worth in that paradigm and when I have to look at OOP.

    As far as I can see, Scala is a mix that provides a bridge between two worlds, where mixing them seems to provide more than keeping structured-and-OO java-based approach. I would like to understand how functional programming could help me to maintain and improve the real life 10000 classes maintained by very different clever persons.

  • http://www.ffconsultancy.com Jon Harrop

    Great article. Shame about the responses.

    “Robert, in all due respect, I think your time would be better spent convincing C# or Java programmers to give functional programming a try than to waste energy in such internecine wars. Given enough determination and superficial knowledge anyone can come up with horrid code in any language. So what?” – Martin Odersky

    I thought it was sad when Tim O’Reilly turned up on my blog trying to tell me how to sell books when our business was booming and he was laying off workers but seeing Martin Odersky here really takes the biscuit. Why would C# programmers care about Scala when it also lacks tail calls, decent type inference and algebraic datatypes (let alone inferred ones like OCaml’s polymorphic variants)?

    “And OCaml? OObscurity. Is it aiming to be the new Perl 6? It’s already there.
    Please, if you’re going to soapbox OCaml, post some great success stories other than wink.com.” – ToddC

    I try to keep a list of OCaml’s biggest industrial success stories here but it just keeps growing (e.g. MLState just shipped their first OCaml product):

    http://www.ffconsultancy.com/products/ocaml_journal/free/introduction.html

    Perhaps the biggest is Microsoft’s imminent productization of a closely related language (F#). No sign of that happening to Scala. Indeed, Scala will be lucky to get tail calls before Sun disappear forever.

  • Pingback: Postfunctional programming language « techscouting through the news

  • Pingback: Scala: Post-Functional, Post-Modern, or Just Perl++?

  • http://www.cs.tufts.edu/~nr/ Norman Ramsey

    Nice work.

  • http://onlinegamblingamerica.com american online gamb

    It is good thing if Scala could supplant Java, the JVM would be in a much better place.

  • wicketmax

    should I learn scala or ocaml?

  • http://enfranchisedmind.com/blog/posts/author/bhurt-aw/ Brian Hurt

    I’d answer ocaml to that question. YYMV.

    Brian

  • wicketmax

    thangks

  • Pingback: Functional Scala: Introduction « brain driven development

  • Marcel Kincaid

    “I’m done here” instead of admitting that you were wrong.

  • Eric

    This blog was written some time ago so I am sure thoughts must have changed some since then. However, I would like to point out that functional and object oriented programming are just programming styles. Programming “Languages” have varying levels of support for certain styles. You can think of OOP, FP, and LP as ideals that are rooted in different computation theoretical ideology. One can program in a functional style in C; also, one can program in an OO style in C using structures quite easily. C, however, lacks many of the nice supporting features that have been developed to make these styles easier.

  • Peter Ashford

    “I thought it was sad when… ”

    …oh, but your response was all class and not at all argumentative.

  • Marc

    Not to mention that there’s also a Scala implementation for .NET.

  • Anonymous

    Erm…that’s basically what Scala does.

    val foo_fun = (a:Int)=&gt;(b:Int)=&gt;a+1
    // &gt; foo_fun : Function1[Int, Function1[Int, Int]]
    val bar_fun = (a:Int, b:Int)=&gt;a+b
    // &gt; bar_fun : Function2[Int, Int, Int]

    is roughly equivalent to Haskell’s:

    foo_fun a b = a+b
    bar_fun (a,b) = a + b

    Also, Scala actually has a very clean currying syntax.

    val baz = foo_fun(3, _)
    print(baz(2))
    val quux = foo_fun(_, 3)
    print(quux(4))
    main :: IO ()
    main = do
      let baz = foo_fun 3 in print baz 2
      let quux = a -&gt; foo_fun a 3 -- Scala wins in this case.
        in print quux 4
  • steve

    @Eric:

    Well, I think the problem with the original article was that:

    a) The author didn’t really knew Scala and wrote really ugly Scala code (instead of code as clean as his OCaml examples) and based his whole claims on it. He didn’t make any effort to correct his examples.

    b) The author thought that “curried-by-default” == “more functional”, although there are exist just as many undisputed functional languages which are not curried-by-default. OCaml, Haskell chose curried-by-default; SML, Scala chose uncurried-by-default, so this is a non-sequitur.

    c) The author had the misconception that OO and FP was somehow mutually exclusive. Now, in 2011, it is broadly established that this isn’t the case, Scala was just the first language where the language designer had invested some deeper thoughts on how to do the integration OO-FP integration right.
    No one ever claimed that Scala is less OO because it is also functional; why should it be the other way around?

    There might be other valid reasons, like better Java interop, which might make Scala code not as succinct as Haskell code, but sadly this point hasn’t played a role in the following debate.

  • Martin

    He’s right though. def x(a:Int, b:Int) = a + b defines a method which takes two arguments and returns a product;not the same thing as let x a b = a + b;;, which allegedly returns int -> int -> int

    The corresponding code in Scala would be def x(a:Int) = (b:Int) =< a + b
    def y = x(1)
    y(2) // 3

  • Guest

    Today we are see many times “OOP failed”. But in the near future we will see the same: “FP failed”. Why? Bcz OOP and FP – both are models of representation of thinking. Nothing else. FP is model from mathematicans, so it’s bad and unpractical – but with very short (and unreadable, so heavy supported) code, only size of FP code is the reason of its popularity. Safe and robust programs (what is need in real industry) looks like Ada, Pascal, D, Eiffel. FP style is “tolerant” to bugs. And falldown of FP popularity is near.

    You said about FP in Scala and show examples with currying, matching… But show they as syntax-forms embedded in language (Ocaml). Where you have funcs, you have currying. Benefits of pattern matching are very controversial. It’s very weak and uncertain attempt to repeat Prolog (even _ is used!). But in Prolog this is the principal other feature: due its bi-direction (absolutely another computation model of Prolog). In FP pattern matching looks naive and inappropriate. And it’s easy to be implemented as equals()/__eq__() overloading and done with “if … else if…”/”switch…” blocks – more control, more readable and the same number of lines IN ANY language! :)So, Scala has all real FP features instead of syntax tricks of them. What is the OOP? Paradigm or the way of code organization (structuring)? And what is the FP? Paradigm? Or code organization (with syntax sugar, tricks, like matching which is not real matching)?In OOP code organization ideas and paradigm are very confused and close (we want to have state – so record, we want to have functions manipulated this state (and avoid names with structure’s name prefix) – so methods, we want to reuse code – so inheritance. Or this is the paradigm?:) ) Cut TYPES SYSTEM from FP and you’ll get all what you have in any another modern language. Well Scala is FP :) Look, closures are bounded state of args, and programmer doesn’t know where is this state, how to change it… But this is the delegates – state is the class fields, method pointer is the delegate – closure. Where is the border? What model is the better? OOP, IMHO is more readable and controlable (and longer as code lines). You want pure FP? No problems! Write in C/C++ in pure FP mannier! In D you can add “pure” modificator to funcs even! You want lazyness, you have them in Scala, D, Tcl even! So, today, border between OOP and FP is thin. Principally we have 3 paradigms only: declarative (predicate calculation), applicative (Lisp – code is transformable data, code is explicit AST) and imperative (FP, OOP…). And todays many-many language has features of FP, FP languages has OOP features and both are different only for compiler creators. So, is the Scala FP?

  • Guest

    Absolutely!

  • Senator Palpatine de Sade

    Well, I’m a newbie to all this – but I believe that the claim of Scala is to mix OOP and functional prog in a manner that allows both the paradigms to be utilized when and as requires. This should not mean that in being ‘functional’ it must absolutely ditch OO features right?

  • http://www.facebook.com/profile.php?id=1386404089 Kristopher Micinski

    FYI That’s not the Y combinator, that’s another fixed point combinator, sort of the U combinator (but also specialized to a particular — call by value — reduction order). You can’t type the Y combinator in OCaml… But you typed a particular fixed point combinator.

  • Steve

    This article is a joke. The author clearly does not know scala. He just poked his head in barely enough to write some god awful code and then rip it apart. You should really give scala a shot. People a lot smarter than you are using it to do some pretty awesome stuff.

  • dxh

    You really have no idea what you are talking about, do you?

  • andr21

    this is a non-sense…then funcional languages is not about functions as first class citizen, closures, lambdas, inmutable states, monads, etc…it’s only about “how feel”??…and yes, lisp (the first fl) doesn’t feel as haskell or ocaml…actually lisp hasn’t curried functions at all…so yes..scala isn’t the most clear and sexy FL, you’re right, but is totally wrong than this is not a functional language because this doesn’t look as haskell or ML or ocaml…is the worst title than I’ve read for a while and the worst argument, note: I’m waiting for your next article: Lisp and clojure are not functional languages (because doesn’t looks as haskell)…

  • andr21

    I ask the same, what is your argument that scala is not a functional language…I’ve work with haskell,f# and clojure and yes..scala is not a sexy FL…is a sexy OOP language..but if you read a book about FL principles you will found than scala fullfills all requeriments for be a full functional language and in any part we talk about “functional syntax”…this article clearly try to create controversy and I’m sure than must be your article with most comments…

  • Yura Taras

    Wow-wow-wow, wait a minute! Pattern matching != functional programming. Currying != FP. ADT != FP. Those are features, grown in FP-world, but not a definition of FP itself. FP is about declarative defining transformations on immutable data using pure functions – and Scala does that – sometimes not in the most concise way possible, but that’s mostly because of limitations of the JVM or hybrid OO/FP paradigm. Take a look at Scalaz library – which ports many Haskell features to Scala and let’s see if you’ll say that ‘Scala is not a FP Language’ :)

  • Yura Taras

    I would say “to know both, you should start from Haskell” :-P

  • Yura Taras

    I would say “to know both, you should start from Haskell” :-P

  • Yura Taras

    I would say “to know both, you should start from Haskell” :-P

  • Pingback: Top 10 Very Very VERY Important Topics to Discuss | Java, SQL and jOOQ.

  • Jonathan Neufeld

    If a language requires “people a lot smarter than x” then its a rather useless language because there aren’t a whole lot of “people a lot smarter than x” in the developer pool. Just talk to a tech hiring manager for a fresh and stimulating perspective on how easy it is to come by senior developers.

    My thoughts about Scala’s ease resonate with David Pollak’s in that I find my imperative Java peers struggle with it a lot and I am concerned that only a very few can become productive with it.

    I like to pick on pattern matching, anything more complex than matching on basic case classes and you end-up with an explosion of line noise that nobody enjoys reading. Maybe that’s the price you pay for the power of decomposing a complex pattern into arbitrarily refined pieces and doing something with those pieces:

    someValue match {
    case Bob(x :: y :: Nil, z @ (_: MyType | _: YourType), rest @ _*) =>
    iReallyShouldntBeDoingThis(x, y, z, rest)
    }