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.
hello :: String -> IO String
hello x =
do
putStrLn ("Hello, " ++ x)
putStrLn "What's your name?"
name <- getLine
return name
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.
-- given definitions:
f x y = y
bot = bot
-- eval:
f bot 3
3
-- given definition:
ones = 1 :: ones
-- eval:
ones
[1,1,1,.....]
head(ones)
1
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:
fibs = 1:1:(zipWith (+) fibs (tail fibs))
lambda calculus
Lambda calculus is the theory behind functional programming. We can view lambda calculus as a minimum language:
exp
= const
| var
| exp exp
| \ var -> exp
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.:
(\x -> x + 1) 3
-- rename x to y, the expression stays the same.
(\y -> y + 1) 3
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.