Learning functional programming in scala

I have no experience in functional programming.

My background -
Python - Experienced.
Java - Contributed to small projects.
C - Small programs.
Scala - Refactored code written in Scala in the OOP style into Java code. Contributed to small projects.

I want to give priority to learning functional programming over learning scala.

Resources I have tried and rejected -
Programming in Scala - Not really looking for a syntax book.
Martin Odersky coursera course - Not as detailed as I would like it to be.
Both of the above do not go into functional programming in too much detail.

Learning path I have been suggested -
Functional Programming in Scala (Red book) - Till Chapter 4
Functional Programming for Mortals
Functional Programming in Scala - The rest of the book

Thoughts?

3 Likes

I would also suggest doing the Scala 99 problems: http://aperiodic.net/phil/scala/s-99/

Brian Maso

2 Likes

I co-lectured a course on FP based on the Red Book (Part 1-3) last summer term, the students mostly also had some Java experience but no FP experience. From that we learned two things, that you may keep in mind while reading:

  • The red book really relies on you doing all the exercises. Some things referenced in later chapters is only explained in the solutions, which are not in the book, just in the repo. So these are mandatory.
  • The chapter on “Purely Functional State” (1.6) was really confusing to our students. We plan to move this to the end next time, after explaining the theoretical background on monads. The further chapters may reference it, but mostly in comparisons that also apply to the chapters before (List/Option/Either), so you should be able to skip and revisit later, if there are understanding problems.

Another book that does an introduction to FP is Scala with Cats, which uses the Cats library instead of Scalaz. It assumes, that you can write basic scala code, but most advanced concepts are explained (e.g. experience with implicits and typeclasses is not required). I have only read the first few chapters yet, but it seems well written.

2 Likes

If your interest is more in FP and less in Scala, I would recommend [http://learnyouahaskell.com/](Learn You a Haskell for Great Good), which is heavily geared toward teaching FP using the purest functional language in common use.

I decided to go this route because I’d rather learn Scala over Haskell.

+1

Though it is completely in a different language, Learn You a Haskell for Great Good helped me tremendously to get a firm foundation in the FP concepts and style that undergird a lot of the Scala language and the Scala standard APIs.

Brian maso

1 Like

Hmm. Well, just to give one example, my path (very recently) has been via Cats. Specifically, I:

  • Learned the relevant bits of the Scala language first. In particular, you have to grok typeclasses and monads before most of the serious FP stuff is going to make sense.
  • Read through the Cats documentation, with an eye towards what each type is for. It’s actually better than most documentation I’ve seen over the years, in terms of giving reasonable motivation of why each of these types matter.
  • Chose a real but manageable-sized project to commit to pure-FP on. (In my case, a new test harness for my main application.)
  • Started with an OO-ish skeleton for that, but early on transformed it to pure-FP, and have been building it up in the weeks since then.

Unsurprisingly, I’ve found that getting hands-on has made a huge difference in terms of understanding the motivation for all of this stuff – both in terms of how to use the primary types (especially State and its variants), and why it’s helpful (refactoring is so much easier in this new system).

2 Likes

Your background and learning objectives, in my opinion, make you a perfect match for this: https://www.coursera.org/learn/programming-languages

This is a free online course teaching functional programming using the Standard ML programming language. You’re thinking, why should I learn Standard ML (SML)? The point is not to try to push you away from Scala, but to use SML as a teaching language to learn statically-typed functional programming concepts, including: an intuition for how type inference works, first-class functions, generics and parametric polymorphism, modules and data abstraction. These concepts are incredibly relevant to Scala as well.

The reason I recommend this particular course is because of the quality of the lectures. Each one is about ten minutes long and is explained clearly, concisely, and gives you a very useful mental model of the topics covered. The lecturer is Professor Dan Grossman at the University of Washington. Highly recommended (even if you skip the assignments–the lectures are that good).

I co-lectured a course on FP based on the Red Book (Part 1-3) last summer term, the students mostly also had some Java experience but no FP experience. From that we learned two things, that you may keep in mind while reading:

  • The red book really relies on you doing all the exercises. Some things referenced in later chapters is only explained in the solutions, which are not in the book, just in the repo. So these are mandatory.
  • The chapter on “Purely Functional State” (1.6) was really confusing to our students. We plan to move this to the end next time, after explaining the theoretical background on monads. The further chapters may reference it, but mostly in comparisons that also apply to the chapters before (List/Option/Either), so you should be able to skip and revisit later, if there are understanding problems.

The Red Book is an excellent book for an individual to learn functional programming with Scala, especially if one wants to dig a bit into how FP works internally. But it is not a good textbook for a lecture-based course because, as the comment above says, it depends upon the exercises being worked out.

I adopted the book as my textbook for a functional programming elective course in the January-May 2016 semester at my university. My students mostly had Java and maybe Python and C experience, but essentially no FP experience. To use the book in a lecture-based course, I found that I needed to reconstruct the chapters with the solutions to many of the exercises for my presentation. I did that for chapters 3-5, but had to shift to a different approach because I had too few hours in the week to devote to class preparation in the last half of the semester.

One student commented that he did not learn as much as he wanted on how to use FP to solve real problems because of too much time learning how to implement the “library” in Scala.

I am teaching the course again using Scala beginning in about two weeks. I do not plan to use the Red Book directly, because of the comment above and my experiences in 2016. I have not yet decided how to approach the course. I would like to push more into more advanced features like futures, actors, monads, without getting so bogged down with the early details. So I am open to suggestions.

It will be a small (maybe 10 students), but difficult group of students, ranging from a third-year undergraduate who probably just has Java plus maybe a little Python and C to several fourth year and graduate students who have had another of my classes that uses Haskell. Most want to learn “multiparadigm” Scala for applications use (e.g., Spark, actors, server-side Web) rather than FP per se.

Scala is undoubtedly the more “practical” language for students to learn compared to Haskell (i.e. more use of Scala by potential employers of my students). But, as a hybrid (“multiparadigm” is the term I typically use), Scala does not force the students to think functionally. They can fall back back easily on imperative ways of thinking.

I likely will use the book named below some during the semester.

2 Likes

It sounds like you had pretty much the same experiences as I had with our course. The course was new and we will only hold it a second time starting end of April, so I don’t have any experience with different approaches, but we have collected some ideas on how to restructure the lecture based on student feedback and exam results (which showed what parts were least understood), maybe some are useful to you.

One student commented that he did not learn as much as he wanted on how to use FP to solve real problems because of too much time learning how to implement the “library” in Scala.

We plan to focus more on an “algebraic” approach, i.e. focusing on the operators a structure like a Monad / Functor / Monoid etc. provides and what laws it obeys, instead of focusing on how to implement it. We will only implement only essential stuff and show usages of those functions instead, leaving other functions as optional exercise. From what I’ve already read, the Cats book seems to be more like that compared to the red book.

Last semester we tried to mix lecture and exercise, having some small 5-minute-exercises of implementing a single function interspersed in the normal lecture (not common in our university, don’t know if this is a usual approach elsewhere). We prepared signatures and required structures in a fiddle. This was well received by the students, but we will probably cut back on the amount of such exercises and/or change what to implement (again, application instead of coding basic building blocks).

As our students did not have experience in any other functional language, most only having learned Java without ever using lambdas, one of the things that the most students had a hard time understanding were Higher Order Functions. We realized this during the State chapter, as many did not understand, where the actual state was in a State monad, because they did not realize, that you pass a function to State’s constructor and not some value of the state’s value type.

It will be a small (maybe 10 students), but difficult group of students, ranging from a third-year undergraduate who probably just has Java plus maybe a little Python and C to several fourth year and graduate students who have had another of my classes that uses Haskell. Most want to learn “multiparadigm” Scala for applications use (e.g., Spark, actors, server-side Web) rather than FP per se.

Our situation is a bit different, we had about 50 students last semester, but also from very different stages of their studys. Additionaly, we also had math students in our course, so we had the full range from “want to learn practical Scala” to “want to learn pure FP and correctnes proofs”). That’s why we will start the lecture with a bit of historic background and lambda calculus next time, as several students said they missed that.

But, as a hybrid (“multiparadigm” is the term I typically use), Scala does not force the students to think functionally. They can fall back back easily on imperative ways of thinking.

We thought of using a compiler plugin, probably WartRemover, to restrict Scala more for the exercises. This can at least prevent usage of vars and some other not referentially transparent parts. We provide an sbt file anyway, as we use kind-projector for type lambdas in the later chapters, and have an automatic online grading system, so the students don’t submit code which would not pass with that sbt config.

Maybe you need more or better examples of problems where the FP approach gives you something you can’t get as easily using other approaches?

I’m surprised people don’t understand higher-kinded functions. Most software engineers should have heard of callbacks.

I’m surprised people don’t understand higher-kinded functions. Most software engineers should have heard of callbacks.

I’m often surprised, how many of our students have never written a single line of code until starting university, and a lot of them don’t do any programming outside of course activities. The mandatory courses are all Java, and mostly algorithmic uses, so it’s not improbable for them to never have used callbacks.

I also think, that the required mode of thinking is different: when you use a callback, that callback is often just code, that is passed the result of the higher order function, when it’s finished. So semantically, it isn’t much different from sequential code in many cases. Even if you have a success and failure callback, thats semantically an if-else. With the higher order functions in monads, the passed function is potentially called several times inside the higher order function, and with the state monad, it isn’t called at all until you evaluate it with an initial state, but stored and used for composing before. That’s a pretty different use of functions as values, compared to callbacks.
Also, unless you have a Javascript (or similarily async language) background, it’s quite possible that you may be able to use HOFs, but have never written one yourself.

Of course, this is just my guess, and my sample size is small :wink:

1 Like

Although I am teaching a small Scala elective in our January-May semester, I taught large (85 student) required course that used Haskell in the August-December semester. Some students did great. More did reasonable. Too many others were still trying to write Java code rather than Haskell at the end of the semester–still struggling with recursion, immutable variables, higher-order functions, pattern matching, algebraic data types, etc. I did not try to teach monads. :slight_smile:

1 Like

Also remember – Java was fiercely anti-function for a very long time, so many peoples’ experience of “callbacks” is by passing an object that has a method to invoke as the “callback”, and a lot of legacy stuff reflects that. It’s much more indirect and far more boilerplatey, and as @crater2150 points out, tends to be used for more restricted problem domains.

This is specifically why, when I tried to write a project in Java in 2007 after 5 years of C#, I wound up giving up in frustration: I found that I could no longer code without easy lambdas. (That was actually what drove me to Scala in the first place.)

It is interesting to note that one of the advantages of Scala for CS1 and CS2 that was noted by one of my non-functionally inclined colleagues who teaches CS1 and CS2 regularly is that it sets students up well to learn other languages. Most of our students take a course on Functional using Haskell in their sophomore year. Moving from Scala to Haskell isn’t a huge shock. Neither is moving from Scala to C++, Java, Python, C#, etc. If you want to try to convince your colleagues to make that change, I’d be happy to recommend some textbooks. :wink:

1 Like

Coming back to the primary question, do I need to try and get a thorough understanding of scala before trying to learn functional programming via the Red book?
Since learning functional programming is my primary goal, should I learn functional programming via some other strictly functional language like common lisp, SML or Haskell and then learn Scala?

Going back and actually looking at the Red Book: technically, no – stuff gets introduced as you go. But be prepared for a slightly tricky ride, and don’t expect to learn Scala from the Red Book. It introduces language concepts as they are needed, and talks about them briefly, but doesn’t really explain them in any depth. You should be prepared to do a bunch of outside reading in parallel with it, especially if you want to apply the lessons of the Red Book to practical, real-world applications.

Also, note that it assumes upfront that you are already a moderately experienced programmer. Concepts like “class” and “method” are used pretty casually, with any particular explanation.

The honest answer is, “I don’t know”. It’s less common for folks to start in Scala with the Red Book, and some who have tried have found it tough going. I suspect it can be done, but it’s not trivial.

I’m on the fence here. I’m a deep Scala enthusiast, but I can’t disagree with other folks’ observation that Learn You a Haskell is a breezier, easier book. (And free online.) It’s not that Haskell is intrinsically an easier language, it’s that this is the tutorial to the Haskell language, so it is deliberately designed to be fairly easy to read and learn from – and since Haskell is pure-FP from the get-go, it necessarily covers those concepts along with the language.

Honestly, you might want to play with both, and have them supplement each other. I don’t actually use Haskell for anything, but I still found the first half of LYAH quite valuable for introducing many of the concepts, before I then went and started applying them to my Scala code…

1 Like

This really raises the question, is there a market for a book with a title like “Learning Functional Programming with Scala” that starts off with a gentler introduction that the Red Book and spends more time introducing aspects of the Scala language?

IMO, yes.

IMO, yes. Scala mixes together concepts from OOP, FP, static typing, and introduces its own concepts on top of those. If you want to focus on FP with a view to transferring concepts to Scala, it makes sense to learn using a simple, academic language that has been successfully used to teach typed FP.