Monday, October 14, 2013

Lessons 27-28 - Haskell and Vim

A couple of days ago we had a lesson where we integrated a bunch of skills. 

We split the iTerm2 window into two panes using cmd-D and then started working on a new program file in the left pane. The coding assignment was to write a Haskell program that asks you "who are you?", then waits for keyboard input and finally greets you like "hello, Juha". 

It is known that there are only 2 hard problems in computer science, namely cache invalidation and naming. We haven't started coding for the browser yet, so for us, there's only naming. After a long consideration, she decided to name our program "housut" (pants). Then she typed it "hosut" and refused to correct the typo. So, we started editing "hosut.hs".

We wrote a single line of code:

    ask=say "who are you"

Naturally it took us a lot of time to decide what we should name our function that asks "who are you". But hey, that's what daddy does at work too. Strugglees with several layers of caches and, of course, naming.
    

The we moved to the right-hand side iTerm2 pane and started the Haskell REPL, namely ghci. Practically that is an interactive environment for running Haskell code, typed on the command-line, or loaded from a source file. We loaded our source file in ghci and called the ask function:

    $ ghci
    Prelude> :l hosut.hs
    Prelude> ask

It worked! But that was definitely enough for that lesson. She ran away and started playing with her sister. But a while later she returned to the computer, started Turtle Roy and drew a rectangle all by herself!

Today we also had a very brief session before sauna. We added a second line to the saved program at "hosut.hs".

    hello = i >>= say

This little function gets user input using the function i and "pipes" the result to the say function, using monadic composition, i.e. the ">>=" function. So there we are, working with Haskell monads in vim. And that was it for lesson 28!

Oh btw it's a pity that people find monads hard to understand. In the example, we were chaining two IO actions together using the monadic bind (>>=). So, for IO and many other monads, the monadic interface just gives you a nice way to "pipe" actions together. An equivalent way to implement hello, using so-called do-notation would be

    hello = do
      name <- i
      say name

That's more like the BASIC programs I wrote as a kid. But why introduce the overhead? Do-notation is just syntactic sugar for monadic composition. Of course, in a more involved example, it would make more sense. Like

    hello = do
      say "what's your name"
      name <- i
      say "what's your salutation"
      salutation <- i
      say ("hello " ++ salutation ++ " " + name)

OOPS, this is starting to become a monad tutorial. ABORT!

No comments:

Post a Comment