This is an old revision of the document!
Introduction to Haskell
Functions in Haskell
In mathematics, functions have a domain an codomain. In Haskell, functions have types or signatures. They often can be omitted in Haskell, but can also be explicitly written as in:
f :: Integer -> Integer -> Integer f x y = x + y
or:
f :: Bool -> Bool f True = False f False = True
The previous example illustrates that we can define functions by specifying a behaviour for given values.
3. Write a function together with its signature, which implements boolean AND:
myand :: Bool -> Bool -> Bool ...
5. Write an implementation for a function ifp
which takes a boolean, expressions $ e_1$ and $ e_2$ and returns $ e_1$ if the boolean is true and $ e_2$ otherwise.
ifp = ...
6. Write a function which takes three integers and returns the largest. Hint - sometimes parentheses are important in function calls.
f :: Integer -> Integer -> Integer -> Integer
In Haskell, we can use the if construct, in a manner almost identical to the above implementation, e.g.
f x = if x == 0 then 1 else 0
The previous function returns 1 if x is equal to 0 and 0 otherwise. A more elegant way is to use guards:
f x | x == 0 = 1 | otherwise = 0
More generally, guards can be used as follows:
<function_name> <parameters> | <boolean_condition_1> = <expression_1> | <boolean_condition_2> = <expression_2> ... | otherwise = <expression_n>
x. Solve the previous exercise using guards
«Explain lists, head, tail»
x. Implement reversal
13. Write a function which extracts the third to last number from a list and returns True
, if that number is odd (hint: the function mod
may be useful)
V f [3,4,5,2,3,9] = False f [3,4,2,1,4,4] = True
«Explain pattern matching»
x. Implement the previous exercise using patterns
14. Implement a function which returns the sum of integers from a list.
15. Implement a function which takes a list of booleans and returns false if at least one boolean from the list is false.
16. Implement a function which filters out all odd numbers from a list.
17. Implement a function which takes a list of booleans and returns a list of integers. In the latter, (True
becomes 1
and False
becomes 0
). Example: f [False, True, False] = [0,1,0]
.
«Explain char and strings»
x. Write a function which removes all empty strings from a list.
x. Write a function which removes all strings of size smaller than 3. Do not use the builtin function length
.
x. Write a function which removes all strings having the third letter equal to 'a'.
x. Write a function which:
- removes all strings which are not names. A name always starts with an uppercase.
- removes the last name from the resulting list of names. A name always comprises of the first name followed by the last name.