Haskell Notes (2)
Monads
A monad is an algebraic structure in category theory, and in Haskell it’s used to describe computations as a sequece of steps, and to handle side effects such as state and IO. It is used to allow actions(e.g. mutable variables) to be implemented safely.
A monad in Haskell consists of a
keyword and a sequence of commands. To extract information from a monad, use 1
do
. Monad is the way to implement IO operations. Note the return type of the hello function is 1
<-
, not 1
IO String
.1
String
In fact a
block is just a syntactic sugar. Won’t go over too much, see more Here.1
do
Lazy
Haskell is lazy, meaning that the evaluation of expressions is delayed until actually needed.
is the simplest infinite function defined. Because of the laziness, if we evaluate 1
bot
we get 1
f bot 3
, but if we evaluate 1
3
we get an infinite loop.1
f 3 bot
For another example, we can define the fibonacci sequence lazily:
lambda calculus
Lambda calculus is the theory behind functional programming. We can view lambda calculus as a minimum language:
variables
Variables are either
or 1
bound
.1
free
- In
, the variable1
\x -> x + y
is bound and1
x
is free. In1
y
- In
, the first1
a + (\ a -> 2^a) 3
is free and the other1
a
’s are bound.1
a
Alpha conversion
Alpha conversion means you can change the bound variables freely without affecting the value of the expression. e.g.:
Beta conversion
Beta conversion is just
the lambda expression. It is done by substuting value for the parameters, i.e. the expression 1
applying
is converted to 1
(\x -> exp1) exp2
.1
exp1[exp2|x]
Eta conversion
Eta conversion says that a function is equivalent to a lambda expression that takes an argument and applies the function to the argument, i.e.:
is equal to 1
(\x -> f x)
. As another example, 1
f
is equivalent to 1
f x y = g y
.1
f x = g
everything is a lambda
In fact, everything (variables, constants, lists, functions, etc.) is just syntactic sugar for a lambda expression. see Link for details.