Tuesday, January 21, 2014

Functional programming for fun

I saw a talk called "Functional Reactive Programming in Elm". This talk shows off Evan Czaplicki's functional programming language Elm, which looks a bit like Haskell and compiles to Javascript. The really fun part is, Evan implements a simple Mario game for us in real time on stage. If you already know a pure functional language like Haskell, just watch the talk. Here's the link: http://www.infoq.com/presentations/elm-reactive-programming. It starts out a bit slow but once it gets going it's a lot of fun. For anyone else, I'll give a bit of background to help the talk make sense.

Under the Canopy, flickr user Jill Clardy, CC BY-NC-SA 2.0
Pure functions have no side effects. They take inputs and write outputs, but they don't hold state or change the values of anything. In a pure functional language, all functions are pure. Since a program with no side effects can't even print "Hello, World" to the screen, you do have to allow side effects somehow. Haskell, for example, uses something called an IO monad, which you could think of as passing the entire IO state to a function, and getting the new IO state returned from the function. I'm not sure I got that right, but my point is that a pure functional language takes seemingly simple actions like writing to the screen or reading keyboard input and wraps them in strange concepts to let them exist in a pure functional language.

In this talk Evan wants to write an event-driven Mario game in a pure functional style. But events represent state change, which isn't allowed in a pure function. In the pure functional world event-driven programming is not called event-driven programming, it is called functional reactive programming. At one point he explains his epiphany, "what if values changed over time?" You might not see what the big deal is. But in pure functional languages, values don't change. If you set x = 5, then x is always equal to 5. If you try to set x = 6 on the next line, that's a compile error. So what if you found a way to encapsulate the concept of a value that changes over time in a pure functional way? That's what he's done with his programming language Elm.

It takes some cojones to write and debug a program on stage in front of a room full of people. Evan Czaplicki does it with style and a good deal of humor.

One more note. Evan presented using a cool piece of software called Prezi that doesn't translate well to PDF slides, and is not visible in the recording. I've been meaning to check out Prezi, because it was really an eye-catching presentation. It's a shame you can't see it in the recording.

No comments:

Post a Comment