Hacker News new | ask | show | jobs
by flomble 2921 days ago
The interesting thing is that in Haskell, the equivalents of Python's `A(B,C)` and `A(B)(C)` are identical: `a b c`. This is because of currying: you're allowed to supply one argument to a function at a time, and you get back a function that takes one fewer argument. So if `add(x,y) = x + y`, then `add(5)` is a function (let's call it add5) so that `add5(y) = 5 + y`, or in Haskelly notation, if `add x y = x + y` then `(add 5) y = 5 + y`. If you write `add (x,y)` in Haskell, then it means a function that takes a single tuple `(x,y)` as an argument.

A(B(C)) would be `a (b c)` or `a $ b c` or `(a . b) c`. The first is the most vanilla way, the second is convenience (basically "evaluate everything after $ first, then plug it in") and the third uses the function composition operator `.`.

1 comments

Nice summary. I would just like to add that `$` and `.` in Haskell aren't part of the language syntax, they're just normal functions/operators, which some people like to use.

We can define `$` ("apply a function to an argument") as:

    f $ x = f x
We can define `.` ("compose two functions") as (where `\x -> ...` is an anonymous function):

    f . g = \x -> f (g x)
Equivalents in, say, Javascript would be:

    function dollar(f, x) { return f(x); }

    function dot(f, g) { return function(x) { return f(g(x)); }
People mostly use `$` because of its precedence rules, which cause everything to its left to be treated as its first argument, and everything to the right as its second, i.e. we can use it to remove grouping parentheses like:

    (any complicated thing) (another complicated thing)
with:

    any complicated thing $ another complicated thing
It's also useful for partially applying, e.g. `map ($ x) fs` will apply each function in the list `fs` to the argument `x`.