August 31, 2026

Haskell for Hobos -- Functions

Haskell is a functional language. As you might imagine, almost everything in haskell is a function. People do sometime say that everything is a function in Haskell. Everything is an expression, but there are primitive data types such as Char, Int, Float, Double, Bool and others.

If I write:

b = 2
I am defining a function that always returns the value 2. Haskell actually has no variables. If I subsequently try to change the value of "b", Haskell will get upset. We cannot have two definitions for the same function. No variables and no loops -- what kind of brave new world is this?

Functions can have 0 or more arguments. Here is a function with one argument:

square x = x * x
Here is a function with 2 arguments:
addemup a b = a + b
You don't get to write functions with a multi-line body that eventually calls return (or potentially calls return in several places). Return in haskell has a utterly different purpose (just to confuse you). A way to add some complexity to functions is to use "let/in" compute intermediate values, such as in this rather contrived example
dist dx dy = 
	let xx = dx * dx
	    yy = dy * dy
	in xx + yy
Another syntax to do more or less the same thing uses "where":
dist dx dy = xx + yy
	where xx = dx * dx
	      yy = dy * dy
Note that you have to be careful and precise with indentation when you have more than one assignment in the where or in clause.

Pattern matching

The idea here is to have different function bodies for different cases. We abused you (without warning) with an example of this already in our loop recursion example. Here is a function that returns true if the argument is 13 and false otherwise:
is13 13 = True
is13 x = False
A long list of patterns can be given. They are all tried in order until one works. It is a bad thing to call a function with an argument it cannot handle. For example this code:
gbu 1 = "good"
gbu 2 = "bad"

main = putStrLn $ gbu 7
This blows up with the following error (and a long backtrace)
pat.hs: pat.hs:(4,1)-(5,13): Non-exhaustive patterns in function gbu
Haskell errors can be long and frightening, but they are actually very helpful and Haskell tries to give you as much information as possible to help you fix the problem.


Have any comments? Questions? Drop me a line!

Tom's software pages / tom@mmto.org