Search code examples
haskellxmonad

What is this expression in Haskell, and how do I interpret it?


I'm learning basic Haskell so I can configure Xmonad, and I ran into this code snippet:

newKeys x  = myKeys x `M.union` keys def x

Now I understand what the M.union in backticks is and means. Here's how I'm interpreting it:

newKeys(x) = M.union(myKeys(x),???)

I don't know what to make of the keys def x. Is it like keys(def(x))? Or keys(def,x)? Or is def some sort of other keyword?


Solution

  • It's keys(def,x).

    This is basic Haskell syntax for function application: first the function itself, then its arguments separated by spaces. For example:

    f x y = x + y
    z = f 5 6 
    -- z = 11
    

    However, it is not clear what def is without larger context.

    In response to your comment: no, def couldn't be a function that takes x as argument, and then the result of that is passed to keys. This is because function application is left-associative, which basically means that in any bunch of things separated by spaces, only the first one is the function being applied, and the rest are its arguments. In order to express keys(def(x)), one would have to write keys (def x).

    If you want to be super technical, then the right way to think about it is that all functions have exactly one parameter. When we declare a function of two parameters, e.g. f x y = x + y, what we really mean is that it's a function of one parameter, which returns another function, to which we can then pass the remaining parameter. In other words, f 5 6 means (f 5) 6.

    This idea is kind of one of the core things in Haskell (and any ML offshoot) syntax. It's so important that it has its own name - "currying" (after Haskell Curry, the mathematician).