September 1, 2026

Haskell for Hobos -- Function composition and more

Haskell is a functional language, which of course means that we can do surprising things with functions!

Function application

You will be surprised to learn what the operator is for function application. It is white space! So to compute a square root:
root = sqrt 5
We have the function "sqrt" and it looks for its argument after the white space. This sort of function application is left associative with very high precedence. I think of it as greedy. So "f a b c" is evaluated as ((f a) b) c). It grabs the next thing, so the following may surprise you:
root = sqrt 8 + 1
This greedily grabs the 8 and so we get 3.8284. The natural fix is to use parenthesis, but there is a better way.

Not so greedy function application

Use the dollar sign! You could use parenthesis, but using the dollar sign generally leads to more readable code. The dollar sign is super low precedence and right associative. So the following are both identical and yield the result we want and expect (namely 3.0).
root = sqrt $ 8 + 1
root = sqrt ( 8 + 1 )
Being right associate means "f $ g $ x" is evaluated as f $ ( g $ x )

Because $ is actually a function (and an infix function at that), you can do surprising things with it that we shouldn't get into quite yet.

Function composition

We can combine functions together into new ones using "." which is the function composition operator (function). The general idea is:
newfunc = func1 . func2
The thing to be careful about is that the type produced by func2 must be the type expected by func1.
As an example, let's try this:
putShow = putStrLn . show
main = putShow 7
This works just fine. Just "PutStrLn 7" would yield an error because it expects its argument to be a string and not an integer.


Have any comments? Questions? Drop me a line!

Tom's software pages / tom@mmto.org