That's why function application syntax in Haskell has no parentheses and commas, compare Haskell's f a b c with Python's or Java's f(a, b, c). This new function can accept yet another list, and it will finally return a new list of type.
The type is not, ->, but -> ->, meaning that (++) accepts one list and returns a function of type ->. Write :t (++) in interpreter, where (++) is a function that concatenates 2 strings together, it will return (++) :: -> ->. Technically speaking, there are no functions of multiple arguments in Haskell, only functions of one argument, some of which may return new functions of one argument. Guess what, Haskell curries all functions by default. Now imagine that you could give only 1 argument to it, and it would return a function? You could use this function later to add this 1 st argument, now encased in this new function, to something else. It's easier than it sounds, for example we have a function of 2 arguments, like (+). (See also my explanation of HOFs using Scheme as an example.) Understanding curryingĬurrying is a technique that transforms a function of several arguments to a function of 1 argument that returns a function of 1 argument that returns a function of 1 argument. So let f = g (+) 2 in f 10 equals 12 and let f = g (*) 5 in f 5 equals 25. Basically, when we call g (+) 2 we create a function of one argument, that just adds 2 to whatever it receives. let g f n = (\m -> m `f` n) f = g (+) 2 in f 10 - returns 12Ī (\m -> m `f` n) construct is an anonymous function of 1 argument m that applies f to that m and n. Below we create a function that accepts a function and an argument and returns another function, which accepts a parameter and returns a result. Writing g a b c = a * b - c, h a b c = a + b / c and so on just doesn't cut it for us, we need a general solution, we are programmers after all! Here how it is done in Haskell: let f g h a b c = a `g` b `h` c in f (*) (/) 2 3 4 - returns 1.5Īnd you can return functions too. Remember, (+) is just a function of 2 numbers that returns a number, there's nothing special about it, so any function of 2 numbers that returns a number could be in place of it. But the function could be more interesting, if we could generalize it, what if we'd want sometimes to sum a and b, but sometimes multiply? Or divide by c instead of subtracting? In usual imperative programming, like in Java, functions can accept values, like integers and strings, do something with them, and return back a value of some other type.īut what if functions themselves were no different from values, and you could accept a function as an argument or return it from another function? f a b c = a + b - c is a boring function, it sums a and b and then substracts c. In mathematics HOFs are called functionals, but you don't need any mathematics to understand them. Haskell, as a functional language, supports higher-order functions (HOFs).