Scala is Not a Functional Programming Language

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.

This entry was posted in Classic, Programming Language Punditry. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

54 Comments

  1. Brian
    Posted May 14, 2009 at 8:01 PM | Permalink

    Piece of advice to everyone thinking of responding to this post. Make sure that, by using your logic and reasoning, I can’t also claim that C is object oriented (not C++, C).

  2. Warren Henning
    Posted May 14, 2009 at 8:12 PM | Permalink

    Scala is hybrid and much of what is considered to be the core language is implemented as a library, which means it won’t scale down to trivial examples sometimes.

    You’d probably actually want to reconstruct the first contrived example as something like:

    object SomeHolderObject {
    def f = (_: Int) + 1
    }

    Moving on to trivium #2, is typing:

    def y = x(1) _

    Really so hard?

    The next example would be

    abstract class Robert
    case class Foo(v: Int) extends Robert
    case class Bar(v: String) extends Robert
    case class Baz extends Robert

    Or whatever as the case may be.

    More characters than OCaml because Scala actually gives you an object system to work with rather than an abortion no one uses like the one in OCaml.

    Scala was built to scale up, not scale down.

    Now, are you going to actually learn Scala before shitting on it or shall we continue comparing pointless trivial snippets?

    (It is suggested, if you wish to continue comparing OCaml and Scala, that you ignore Xavier Leroy’s insanely retarded views on concurrency, e.g., http://caml.inria.fr/pub/ml-archives/caml-list/2002/11/64c14acb90cb14bedb2cacb73338fb15.fr.html ).

  3. Posted May 14, 2009 at 8:20 PM | Permalink

    @Warren

    I’m not saying that OCaml is the greatest language ever and people should be using it. I’m just using it as a point of contrast between a functional language and an object oriented one in order to call out that Scala isn’t functional.

    As for your re-write: the problem is that you have to know at the point of defining f whether or not it is intended to be used in currying. The true power of currying is the ability to cajole functions into the form you need, even if that’s not their native form, which means manipulating functions which didn’t foresee their curried usage.

    So, unless you’re advocating writing every function with (_:Type) instead of parameters (which is a valid — if rather ugly — stance), your example doesn’t really work. All it shows is that if you expect a function to be curried, there’s a syntactic nicety to make currying work okay.

    Of course, the other issue is that if you don’t want to work the f function as a curried function, you end up with this popular Scala oddity:

    f(1)(2)

    See foldRight for a common example of this situation (although another syntactic nicety works around that to a certain extent, too — the ability to substitute { } for ( ) in many cases makes the second argument look like a dangling block).

  4. Warren Henning
    Posted May 14, 2009 at 8:41 PM | Permalink

    Pure functional languages make functional programming as elegant and concise as it can be. Scala supports many of those idioms but doesn’t have as much syntactic sugar for them because functional programming support is only one of Scala’s design goals, not the only one.

    How does “common idioms are slightly or moderately less concise” mean “doesn’t support”? .NET languages’ support for lambda expressions isn’t as elegant as in OCaml, Haskell, or Scala but they’re still there and worth using when it’s the natural thing to do, even if it will be a few more characters than if special support had been added.

    I’ve been using functional languages for about 3-4 years now and I rarely use currying. It seems like you’re nitpicking at things that don’t really matter – when heavy Scala users complain, it’s not about currying.

    The real reason Scala has currying in it the way it does is so you can use it to build lightweight control structures, like the loan pattern: http://scala.sygneca.com/patterns/loan – aping Haskell and OCaml at every turn is not how Scala is normally used. Scala code, indeed, is not ported pure functional code with classes as namespaces, it actually mixes functional and object-oriented idioms freely depending on what’s appropriate.

    You went out of your way to cherrypick parts of Scala you didn’t like, implied that that the feel of using a language stems entirely from one-liners, and then made them as ugly as you could while conveniently ignoring how the two actually compare for real usage on real projects because you know OCaml’s libraries and its runtime suck. Bravo.

  5. Posted May 14, 2009 at 9:03 PM | Permalink

    @Warren

    I never said Scala should mimic Haskell or OCaml. But if you are missing major features that make up the backbone of those languages, are you really in the same paradigm?

    Maybe my point would be clearer this way — technically, what is your argument that Scala is a functional language?

  6. Posted May 14, 2009 at 9:32 PM | Permalink

    “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.”

    Errr… how does Scala put JVM back in the lead when F#–an Ocaml clone–is available on CLR now and due to ship with Visual Studio 2010?

  7. Posted May 14, 2009 at 9:33 PM | Permalink

    Things aren’t quite as verbose as you make them. I’ll paste in some Scala interpretter sessions. OCaml’s:

    let f x = x + 1;;

    looks like this in Scala:

    def f(x: Int) = x + 1

    For example:

    scala> def f(x: Int) = x + 1
    f: (Int)Int

    scala> f(2)
    res0: Int = 3

    You can do currying in a few ways in Scala. For OCaml’s:

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

    You can either define a function with two parameter lists:

    scala> def x(a: Int)(b: Int) = a + b
    x: (Int)(Int)Int

    scala> x(1)(2)
    res1: Int = 3

    To leave out a parameter in Scala, you need to put an underscore to signal your intent to actually leave one out. This is because Scala to have good cross compatibility with Java libraries needed to kind of adopt the overloading rules. So you could have an x method with one parameter and an x with two. So it doesn’t work to just do what they do in languages where currying is the default. So it looks like this:

    scala> val y = x(1) _
    y: (Int) => Int =

    That underscore tells the compiler I did indeed mean to leave off the 2nd param, so I get currying:

    scala> y(2)
    res2: Int = 3

    Another way to do currying is to just put both parameters in one parameter list, like this:

    scala> def x(a: Int, b: Int) = a + b
    x: (Int,Int)Int

    Then put an underscore just for that parameter that you want to leave out. You also have to specify the type in that case too, again, because of overloading (the overloading was a compromise to be compatible):

    scala> val y = x(1, _: Int)
    y: (Int) => Int =

    scala> y(2)
    res3: Int = 3

    The set of case classes you showed is correct, except you don’t need to seal the subtypes. (And you don’t need those semicolons either!) It could just be:

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

    That is more verbose than OCaml’s:

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

    But although I don’t know OCaml, I suspect there’s more you can do with case classes. You can put behavior in them. You can subclass them too. What they were talking about removing was letting you subclass a case class with *another case class*, but you’d still be able to subclass them. So you get the pattern matching plus all the OO stuff.

  8. Posted May 14, 2009 at 10:25 PM | Permalink

    @stephenjudkins

    The reason I put “sealed” in the case classes is because if I don’t put “sealed”, I don’t get warnings on incomplete cases in my matches. That automatic detection of application incompleteness is a huge win for static typing of functional apps, although I mostly use that check in concert with algebraic data types: when I change the type, the compiler tells me where I need to update my code.

  9. Posted May 14, 2009 at 10:39 PM | Permalink

    @everyone noting the x(1,_:Int) example

    Okay, I didn’t know that syntax. This gets me to another issue (Scala’s confusing and surprising syntax), but that’s not a very good issue because it can be written off as “Robert can grok Perl, OCaml, Java, Ruby, and Groovy, but Robert is too stupid to grok Scala”.

    That way of partially applying functions is much cooler. It’s got two limitations which, when combined, make it back to being very OO-y:

    1. It assumes you know the number of elements, and the type of those elements. Such assumptions are pushed off quite a bit.
    2. It’s not very mathematical — in mathematics, partial application means precisely that. In this case, we’re not so much partially applying as using syntatic sugar to create a shorthand.

    But that does address the ugliness at least a bit. Still not as nice as OCaml/F#’s approach, but there you go.

  10. Posted May 14, 2009 at 10:49 PM | Permalink

    @gclaramunt

    I don’t have a hard and fast rule which says what is a functional language and what isn’t: if I did, I’d have put it into the post. The point of my post is that coming from a background where I’m comfortable in lisp, OCaml, and a very FP-y dialect of Perl, it’s odd to jump into a purportedly functional language and discover such a different feel. Over time, having people (e.g. Dick Walls of Java Posse) talking about how mathematical and functional Scala is really has really started to drive me crazy.

    If you want to sell Scala as a hybrid OO/functional language, that’s fine. Groovy also sells itself that way (given the proper audience), and it’s certainly fair enough in both cases.

    Also, please re-read the tail of my post if you think I’m just hating on Scala: I’m really not. I’m just disagreeing with its common sales pitch as the go-to functional language for the JVM.

  11. Posted May 14, 2009 at 10:56 PM | Permalink

    @Bill

    BTW, you have to seal the case classes in addition to the abstract class if you inherited from the case classes. And while you certainly can do more with case classes than you can with variant types, I note that the things you can do are all OO things, so that doesn’t help the sales pitch that Scala is a functional language.

    You seem to have fallen in the trap that other people fell into: I’m not talking about Scala being horrible, or even saying that the design decisions that were made are necessarily bad ones. I’m just saying that Scala is an OO language with functional accents, not a functional language. It feels much more like Ruby or Groovy (or Java the way I write it) than like OCaml or Haskell.

  12. Posted May 15, 2009 at 12:33 AM | Permalink

    Open recursion is not an especially OO concept, so your second “point” is wrong. You can do open recursion in functional languages just fine too. Functional languages let you close up the recursion as you see fit, possibly delaying it until runtime, whereas OO tends to require open recursion at run time.

    The “FP” view of open recursion can be very simple, here’s the Y combinator in OCAML and using it to implement factorial:

    # let rec fix f = f (function x -> fix f x);;
    val fix : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b = 
    
    # fix (function fact -> function n -> if n == 0 then 1 else n * fact (n-1)) 5;;
    - : int = 120
    

    One popular application for open recursion in FP is memoization and dynamic programming. For example, you can express the Fibonacci function as an open recursion, apply it to the Y combinator to get an atrociously slow exponential time implementation; or write a memo combinator to get an reasonably acceptable linear-time solution. I don’t think you can write a combinator to produce the logarithmic-time fast Fibonacci algorithm without seriously breaking abstractions, though…

    Ken Knowles has a really cute example of open recursion: <a href=”http://www.kennknowles.com/blog/2008/05/07/ctl-model-checking-in-haskell-a-classic-algorithm-explained-as-memoization/”?CTL Model Checking in Haskell: A Classic Algorithm Explained as Memoization

    • Posted May 15, 2009 at 9:35 AM | Permalink

      @Leon P Smith

      I need to check into that way of viewing open recursion — basically, you’re deconstructing the arguments into function arguments (in a very lamdba-calculus like maneuver), and I didn’t realize that qualified as “open recursion”, since the variation of the root type is a lot more explicit. I took Martin O’s declaration that open recursion was painful in FP as consistent with my own understanding of open recursion (which came in passing from the OO section of my Programming Languages course back in college), but I suppose that functional approach works the same way. That’s actually pretty similar to the way JavaScript deconstructs things, which I talk about in March’s JSMag, so it shouldn’t have surprised me.

  13. Posted May 15, 2009 at 12:36 AM | Permalink

    @bascule

    As a one-time OCaml hacker and growing F# fanboy, I’m very aware that you can fudge towards one way or towards the other. But ultimately, there’s a different feel to imperative vs. applicative languages: between working on the data and manipulating/defining functions that define the path. Like I said before, Scala feels much more like Ruby or Groovy than OCaml, Lisp, or Haskell. This is a very intentional design decision: Martin O set out to create a fixed Java. And you aren’t going to end up in OCaml/Lisp/Haskell land if your starting point is Java.

  14. Posted May 15, 2009 at 2:21 AM | Permalink

    I realized after I posted that I wrote currying when I should have written partially applied function. Currying is the multiple argument list technique: (a: Int)(b: Int). The underscore syntax indicates functions are being partially applied. You can do that whether or not a function is curried.

    On the sealed question, perhaps you didn’t show the whole file. But if that was the entire file, then you wouldn’t need sealed on the case classes, because sealed means that the only allowed subclasses are in the file. If there are no subclasses in the file, then no need for sealed. Although if you want no one to subclass it at all, you could put sealed I suppose, but I’d put final.

    On the main point, I say “Scala is a pure object-oriented language and a full-blown functional language.” It is pure OO in the sense that every value is an object and every operation is a method call. It is a full-blown functional language in that it has all the usual functional language features. However, that doesn’t mean it *feels* like other functional languages, especially like pure functional languages. It’s definitely a hybrid. I don’t agree that it isn’t a functional language, but I would agree with “Scala is not a pure functional programming language” or “Scala doesn’t feel like a pure functional language.”

  15. pedant
    Posted May 15, 2009 at 2:46 AM | Permalink

    In the spirit of the article’s pedantry, it’s ‘led’ not ‘lead’.

  16. ToddC
    Posted May 15, 2009 at 3:19 AM | Permalink

    Academic pissing contests become boring quickly, how about some code that people can download and apply? The Scala challenge and Hadrop’s garabage code are useless, but interested users will want to see that the original challenge is posted with a working Lift implementation on google code, search for it as rlambda:

    http://code.google.com/p/rlambda/

    And for what it’s worth, Scala runs on the .Net CLR, but Scala programmers won’t have to worry about being burned as all other M$ languages. Every M$ language has only made “progress” by want disregard of backwards compatibility. The one thing M$ has done, is consistent broken their APIs. Probably to appear “hip” to new kids and old guns who never made it past VB. Can’t wait till M$ screws up more languages that people never use like F#, Iron Python. Care to defend the glorious changes/forced incompatibilites between any of the 4 versions of C#?

    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. Or hey, how about some usable code, a live demo that move beyond academic one liners.

    • Posted May 15, 2009 at 9:45 AM | Permalink

      @ToddC

      Read my post again: I didn’t write what you seem to think I wrote. I’m not sure why you’re so violently defensive about Scala in the context of other languages, but we’re less enemies than you think we are.

  17. Henrik Huttunen
    Posted May 15, 2009 at 3:20 AM | Permalink

    It’s obvious you have a different opionion what a functional programming language is. And you haven’t given the optimal solutions in Scala. Plus you don’t take into account that sealed classes are more than algebraic types. And it’s not such a big deal in definition site. The use site is much more interesting. I also wonder whether OCaml has extractor patterns?

    Some constant syntactic noise doesn’t make Scala non-functional. Well you got your attention.

  18. Martin Odersky
    Posted May 15, 2009 at 3:29 AM | Permalink

    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?

    • Posted May 15, 2009 at 9:42 AM | Permalink

      @Martin O

      There are plenty of blog posts and conference sessions out there convincing people to use Scala. And I think that’s a great thing, because if Scala could supplant Java, the JVM would be in a much better place (as my original post says). People keep acting like I’m hating on Scala here, I’m not: my point with this particular post was simply that if you come to Scala expecting to find something that felt like OCaml/Haskell but ran on the JVM, you will be disappointed.

      As far as convincing people to give functional programming a try — Brian and I have been engaged in pushing the OO->functional adoption route for years (cite, cite, cite, cite), and I’m actually kinda tired of it. So I’ll leave evangelism to someone else these days.

      BTW, what are the possibilities of getting algebraic data types into Scala?

  19. Darryl
    Posted May 15, 2009 at 3:36 AM | Permalink

    @Robert
    Is the Scala approach to currying (by marking missing arguments) more flexible than the haskell/ocaml approach? ‘Cos you can pick and choose which args you want to partially apply? I understand the more venerable history of the latter, but to me the former seems possibly more intuitive…

  20. Posted May 15, 2009 at 4:35 AM | Permalink

    While I agree in general that Scala is not a functional language (a term which no one seems to be willing to define, so as to render actual discussion useless and leaving us with mere rants), the following section is ridiculous:

    “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.”

    The OCaml definition is no more “direct” than Scala’s. It happens inside a module. Due to Scala’s unification of objects and modules, the Scala version *also* happens inside a module. They’re exactly the same. The fact that OCaml implicitly wraps every file in its own module and Scala doesn’t has no bearing on the question of whether OCaml is somehow more functional than Scala, and suggesting it does is laugable.

  21. Posted May 15, 2009 at 4:43 AM | Permalink

    Incidentally:

    # let f (x, y) = x + y ;;
    val f : int * int -> int =
    # f 1;;
    Error: This expression has type int but is here used with type int * int

    Why precisely are you complaining about having to use different syntax for curried vs. non again? The same is true in almost every functional language – it’s certainly true in Haskell, OCaml, SML and everything else I can think of that a function taking a tuple of parameters is distinct from a function taking curried parameters.

    It happens not to be the default style in Scala to use currying (and I agree the syntax seems unnecessarily brackety when you do use it. But if you’re going to use brackets as an argument against something being functional, I guess Scheme is tantamount to C). Currying isn’t the default style in Scala, but it’s not the default style in SML either. Is SML thus not functional?

    • Posted May 15, 2009 at 9:28 AM | Permalink

      @David

      You’ve got a mistake in your OCaml example:

      let f(x,y) = x + y;;

      See the type that came out? int * int -> int? That means you’ve declared a function which takes a tuple of two ints and returns an int.

      The type of my example is different:

      let f x y = x + y;;

      That’s int -> int -> int, which can alternatively be thought of as a function that takes one int argument and returns a int -> int function, or as a function that takes two int arguments and returns an int.

  22. Matt
    Posted May 15, 2009 at 6:00 AM | Permalink

    Not really following your argument, I’m afraid.

    1) Scala sticks its named functions as methods on objects — so? It is an OO language, so it’s not surprising it uses objects as its system of organising where functions go. Doesn’t mean it can’t do FP.

    2) It has traits — OK, but, again, does having an OO feature mean that Scala does not support FP?

    3) Currying and ADT syntax is more verbose than the likes of O’Caml — still, it does directly support those features, so why does verbosity disqualify Scala from being a functional language?

    In truth, I suspect declaring Scala dogmatically to be FP or not FP to be largely an unfruitful exercise in debating definitions. It’s clear that Scala has lots of features designed to allow people to program in a functional style on the JVM; for me, that’s the interesting point. If someone then wants to say, therefore, that Scala is a functional language, why shouldn’t they?

  23. Nick C
    Posted May 15, 2009 at 7:51 AM | Permalink

    Very minor pedantic spelling point: “how does Scala fair?” -> “how does Scala fare?”

  24. DavidLG
    Posted May 15, 2009 at 8:04 AM | Permalink

    Which Scala enthusiasts are the ones so wrongly calling Scala a functional language? If it’s the functional programmers, I say let them get excited about the functional features of the language if they feel so moved. What other JVM language do you prefer for writing software more productively in a functional style?

    That said, methods are more fundamental in Scala than functions, it’s true. Function types and compact syntax for function literals (i.e. lambdas) are crucial, but mainly for parameterizing objects and methods, the way I see it.

    Scala strikes a balance between imperative and functional styles with the goal of being good at scaling up to large projects. I think they do that admirably. I don’t think easing up on the OO would help.

  25. Posted May 15, 2009 at 8:55 AM | Permalink

    @Robert Fisher

    “The point of my post is that coming from a background where I’m comfortable in lisp, OCaml, and a very FP-y dialect of Perl, it’s odd to jump into a purportedly functional language and discover such a different feel.”

    Isn’t that a bit like saying the following about Pascal? “I come from a background in Fortran, Basic and a very Imperitive-y dialect of APL; it’s odd to jump into a purportedly imperative language and discover such a different feel”. Are you certain you’re not confusing form for (ahem) function?

  26. Posted May 15, 2009 at 9:28 AM | Permalink

    If you survey the landscape of functional languages you’ll find no agreement on your issues. Erlang is functional and requires functions to be defined in modules. Scheme is functional but makes partial application substantially harder than Scala does.

    As far as I can tell, Scala meets the definition of being a functional language by the only definition that covers all of Common Lisp, Scheme, ML, Haskell, Erlang, etc. That definition is simply that functions can be manipulated as first class values.

    • Posted May 15, 2009 at 10:13 AM | Permalink

      @James Iry

      If that’s the definition you want to run, then that’s fine. But now you’ve just declared Perl, Groovy, and Ruby to be functional languages, too. That’s a bit wider a net than I’m willing to cast.

      This is why I’m using the porno approach, and saying that the feeling of Scala isn’t a “functional programming language” kind of feel — it’s an OO feel. And I tried to show some examples about why that’s true.

      Requiring things to be in modules isn’t an OO approach (OCaml, for the record, creates implicit modules based on file names). But Scala’s singleton objects are not the same thing as modules (e.g.: state change, symbol redefinition), and so putting all functions into singleton objects gives a different kind of feel. The word “object” being right there at the start of the declaration kinda pushes it that way, too.

      BTW, Lisps are a different kind of functional language. They’re not mathematical/declarative in the same sense ML/Haskell is — instead, they’ve got this pervasive code-as-data thing which works differently, but to a similar end effect.

  27. Posted May 15, 2009 at 10:41 AM | Permalink

    @Robert,

    ML is not a purely declarative language. It’s impure and has imperative aspects. Same with Scheme.

    I’ve seen and written plenty of purely declarative Scheme. I have personally written plenty of declarative Scala as well.

    You’re point about “code is data” makes no sense as there is a macro facility for Haskell (called Template Haskell). Further, while a pleasant enough syntactic treat, macros don’t really change the core semantics of the language or change whether it can be called functional or not.

    I’m also not following your point about modules and state. In SML a module can certainly include a mutable reference. The fact that the keyword in Scala is “object” instead of “module” is a thin veneer of syntax.

  28. Posted May 15, 2009 at 10:46 AM | Permalink
  29. Posted May 15, 2009 at 11:39 AM | Permalink

    @James Iry

    Did I ever assert ML — especially OCaml — was pure? That’s obviously false, especially for OCaml (the “OCa” bit being all about objects). Languages certainly draw from paradigms other than their own, and that’s a position of strength — dogmatic identification with one paradigm is interesting for research and certainly pushes the boundaries (SmallTalk with OO, Haskell with functional), but sometimes borrowing from another paradigm is useful.

    And modules != static objects.

    object Foo {
      def baz = 3
      def bar():Int = { this.baz }
    }

    See that this? That’s a huge deal, and it’s OO.

    @Everyone

    I’m confused about this two-pronged push in the flames responding to this post — on the one hand, people seem personally offended that I suggest Scala is an OO language; on the other, people seem to praise Scala’s OO nature with functional accents as a key strength.

    And almost uniformly, people seem to think that I’m hating on Scala. I’m not. I’m really not sure how And don’t get me wrong: as a JVM language, Scala is a huge step forward becomes Scala hating, but there we go. I’ve even offered to write “I LOVES THE SCALA” 500 times on a blackboard during Martin O’s JavaOne talk, if that’s what it takes to prove it.

    @Everyone (Part 2)

    In thinking about what feels different between Scala and OCaml/Haskell (partially in response to comments, partially in response to David MacIver calling my argument “bad”. I don’t have a definition for what I mean by “functional language”, and without predetermined axioms, any definition is ultimately baseless anyway. But the feel starts with applicative programming instead of imperative programming, and it involves mangling functions to make them line up more often than working with data (which is kinda-sorta-not-really function-level programming). If you’re comfortable in a language and you still don’t see the point of flip, partial function application, and tail calls, then the language you’re comfortable in isn’t a functional programming language*.

    The fact that Scala doesn’t have that feel does not mean Scala is a bad language. It just means it’s not a functional language. It’s an object language with functional features, just like OCaml is a functional language with object features. I really don’t see why this is so controversial.

    * Or you’re in a Lisp variant, but that’s a very different kind of functional programming, as I talk about above.

  30. Posted May 15, 2009 at 11:49 AM | Permalink

    No, I haven’t made a mistake in my OCaml example. I knew exactly what I was doing. You posted an OCaml example and a Scala example which didn’t do the same thing. I posted an OCaml example which corresponded to your Scala one which demonstrated the effectively the same error as the Scala example occurs in OCaml.

  31. Posted May 15, 2009 at 11:50 AM | Permalink

    As an incidental point, in Scala 1.0 the top level “object” construct was written “module”. The name changed in 2.0, the semantics didn’t.

    • Posted May 15, 2009 at 1:28 PM | Permalink

      @David R. MacIver

      This OCaml code (which you provided):

      let f (x,y) = x + y;;

      Corresponds to this Scala code:

      def f(x:Tuple2[Int,Int]) = x._1 + x._2

      Note the type signature on the OCaml code: int * int is “tuple of int, int”. So, based on that code, you’re arguing that OCaml can’t easily partially apply tuples. Granted.

      I see where you’re confused — OCaml’s tuple syntax is both visually and practically similar to what Scala creates when it defines a method. Now, you can pre-curry the function by writing the curried form explicitly, but 1) as I previously argued, that defeats the point of partial function application, and 2) you now have a different type signature, with a very different usage pattern.

      def g(x:Int)(y:Int) = x + y  
      // g: (Int)(Int)Int
       
      def h(x:Int, y:Int) = x + y
      // h: (Int,Int)Int
       
      h(1,2) 
      // res0: Int = 3
       
      g(1)(2)
      //res2: Int = 3
       
      g(1,2)
      /* :6: error: wrong number of arguments for method g: (Int)(Int)Int
             g(1,2)
             ^
      */

      One of my points about it not feeling like a functional language is that function manipulation is a bit awkward. Note that in OCaml, we’ve got some Schroedinger typing going on — the type of let f x y = x + y is int -> int -> int, which doesn’t determine arguments or return type until the call site. If you call f 1, you’ve now induced f to be a function that takes one integer and returns a function mapping an integer to an integer. If you call f 1 2, you’ve induced f to be a function that takes two integers and returns an integer.

      These kinds of stunts are what make working with functions really intuitive and easy in what I’m considering a functional language, but it’s simply not that nice in Scala, which is why I don’t consider it a functional language, and why I chafe so badly when people push it as one.

      If the OCaml compiler was stupider, this Scala code:

      def f(x:Int)(y:Int) = x + y

      Would correspond to:

      let f x = function y -> x + y;;

      …but the OCaml compiler reduces int -> (int -> int) to the type equivalent int -> int -> int automatically.

      And singleton object != module. See above, or just ask yourself: “Got this?”

  32. Posted May 15, 2009 at 2:32 PM | Permalink

    As mentioned, I find language wars increasingly tedious. I’m done here.

  33. Tracy
    Posted May 15, 2009 at 3:56 PM | Permalink

    Robert wrote:

    “If you call f 1, you’ve now induced f to be a function that takes one integer and returns a function mapping an integer to an integer. If you call f 1 2, you’ve induced f to be a function that takes two integers and returns an integer.”

    In the second case, isn’t f actually still taking one integer and returning a function; that returned function takes the second integer as its argument?

  34. Posted May 15, 2009 at 4:12 PM | Permalink

    @Tracy

    You could think of it that way, too, although if that’s the way you’re thinking about things, there’s no way to create a multi-argument function in OCaml.

  35. Posted May 15, 2009 at 4:27 PM | Permalink

    @David

    I know you said you’re gone, but I think I get what you’re talking about. What you’re saying is that the normal, Java-looking way people write multi-parameter Scala functions is really writing a function that takes a tuple, and so the “natural” way of writing parameters in Scala is really the pre-curried form. Therefore, the natural way of calling them would also be in the curried form — each argument to its own parenthesis. Assuming all Scala code is written with each argument to its own parenthesis, my complaint about partial function application sucking in Scala would be rather bogus.

  36. Brad Buchsbaum
    Posted May 16, 2009 at 10:17 AM | Permalink

    To use a particularly trite phrase (favored by professional athletes, CNBC commentators, and movie actors) — Scala: “is what it is”. Even better: “Scala is what its incredibly detailed spec says it is”. Perhaps Odersky has been insufficiently assiduous in describing precisely what scala “is”. You be the judge: http://www.scala-lang.org/docu/files/ScalaReference.pdf.

    Or, perhaps, “it depends on what the meaning of is, is” to quote a former politician.

    Scala has a family resemblance to some fairly prototypical functional programming languages, e.g. Haskell. It has a family resemblance to Java, C++ etc. Its stated goal is to blend the object and functional styles in a hybrid “object-functional” amalgam. It’s is an attempt at synthesis. It is a proud mongrel. It is what it is.

    Now, we might equally argue whether, say, Byron should be classified as a Romantic poet. After all, his style more resembled that of Pope, George Crabbe, Thomas Moore than it did, say, to Wordsworth or Keats. On the other hand his overall feel and temperament is decidedly Romantic — for instance the Childe Harolde poems.

    Oh yeah, how do we define a “Romantic poet”, exactly, anyway?

  37. Posted May 16, 2009 at 1:07 PM | Permalink

    Just to be clear: there’s many reasons why Scala could be considered not functional enough but your examples (particularly the curry/partial application one) are far from convincing.
    Last week I was reading http://matt.immute.net/content/scala-vs-skalleh bumping against the limits of Scala’s type system. And I’m pretty sure that Tony Morris http://dibblego.wordpress.com/ can give you plenty of arguments.
    Or just change the title to “Scala is not OCaml” :)
    Anyway, I’ve enjoyed the debate.

  38. Posted May 16, 2009 at 8:59 PM | Permalink

    @Gabriel C

    Thanks for the links. I was just trying to get at the “gist” of the issues in a way that would make sense to people who weren’t familiar with functional programming: I presume those who know Haskell/OCaml/F#/whatever recognize Scala’s non-functional nature rapidly enough, so it’s not worth selling to them. Those links do go into a lot more expansive detail (which is cool), although they presume a pretty solid familiarity with functional programming.

    @Brad

    Insofar as people keep acknowledging that Scala is a mongrel, I’m perfectly happy. I just get cranky when people confuse Scala for a normative statically typed functional language, or talk about how “mathematical” it is (that’s a Dick Wall-ism).

  39. Posted May 17, 2009 at 3:24 PM | Permalink

    On the other hand, I’m in the process of learning Haskell, and I find Scala still “functional enough”: currying, first class and high order functions, pattern matching, etc.
    The “filp” function in Haskell and Scala is the same (minus type declarations). Anyway, I’ll bet that for a Haskell fan, even Ocaml is not functional enough (side effects? objects??…???)

  40. Posted May 18, 2009 at 11:05 AM | Permalink

    @Gabriel C

    They’re the same — assuming you pre-curry your function signature, and modulo type declarations. Those kind of gotchas/awkwardness is exactly what I was calling out in this post. David is right when he asserts that my basic point is that declarative/functional programming in Scala is harder than it needs to be, but I’m actually going further than that — I’m saying functional/declarative programming is harder to the point where OO solutions are more natural to the language. Hence my original assertion.

    @Everyone

    Definitely check out The Purpose of Scala’s Type System. It’s very interesting conversation about design decisions behind Scala’s type systems. Also, note that Scala is competing in the Scripting Language Bowl at JavaOne (more info here) — it will be interesting to see what kind of solutions Martin O cranks out when push comes to shove.

  41. Willis Blackburn
    Posted May 25, 2009 at 3:13 PM | Permalink

    Okay, let’s stipulate that your thesis is correct: Scala is not a functional programming language.

    So what?

    A programming language is for writing applications and should be judged according to its suitability for writing the application at hand. Scala is a language that allows developers to utilize most if not all of the idioms of a pure-functional language while still supporting development in the imperative style and compatibility with a decade’s worth of tools written in Java. It’s a language that is well-suited to writing the types of applications that people actually write.

  42. Posted May 25, 2009 at 3:27 PM | Permalink

    @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!

  43. Posted May 25, 2009 at 3:34 PM | Permalink

    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.

  44. Posted May 25, 2009 at 3:52 PM | Permalink

    @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.

  45. Posted May 30, 2009 at 9:26 PM | Permalink

    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.

  46. Yves Bossel
    Posted October 16, 2009 at 8:26 PM | Permalink

    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.

  47. Posted December 27, 2009 at 5:48 PM | Permalink

    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.

  48. Posted May 1, 2010 at 8:47 PM | Permalink

    Nice work.

9 Trackbacks

  1. [...] Fischer has a post on his blog: Scala is not a functional language. It’s not the first time this idea has come up. It’s not an idea entirely without [...]

  2. By WebDevGeekly » Blog Archive » Episode 14 on May 25, 2009 at 1:02 PM

    [...] Scala not a functional language? [...]

  3. By Web Dev Geekly #14 | Enfranchised Mind on May 25, 2009 at 9:25 PM

    [...] programming font fetishists, and the promise of CouchDB. We didn’t actually get to the Scala Is Not a Functional Language conversation due to a grill calling Michael Kimsal away from us, but we’ll be sure to get to [...]

  4. [...] working on two awesome posts, including a very cool follow-up to Scala is Not a Functional Programming Language. Awesome takes time, though, so they’re not ready to go [...]

  5. [...] the Dynamic Language EnthusiastLet Me Save You $40: Here's How to Be HappyWhat good is a CS degree?Scala is Not a Functional Programming LanguageWeb Dev Geekly #14Postgres for the win!I Made This For All My Perl PeepsProblems with Hash TablesThe [...]

  6. By Fragments forthcoming « Doug Milam on September 14, 2009 at 11:04 PM

    [...] I see that Twitter has moved to Scala and is getting away from Ruby, of Ruby on Rails fame. Talbott’s post about Ruby is worth the [...]

  7. [...] Postfunctional programming language Robert Fischer published an article titled “Scala is Not a Functional Programming Language“ [...]

  8. [...] I complained that Scala did not seem to be very functional to me, but I didn’t really know how best to express what was fundamentally wrong with it. I did know that if “functional languages have a fixed set of features” like Scala’s creator, Odersky, claims, then it wasn’t simply “first-class functions in there, function literals, closures”, “types, generics, [and] pattern matching”. Scala has missed the functional boat in some basic way. [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">