Lazy Evaluation
In an older version of the base library the function
intersperse
, which places an element between all elements of a list, was defined as:= [] intersperse _ [] = [x] intersperse _ [x] :y:ys) = x : e : intersperse e (y:ys) intersperse e (x
What would you expect the result of the expression
intersperse 'a' ('b' : undefined)
to be?Can you give a definition of
intersperse
which is less strict?
Given the data type of binary trees:
data Tree a = Leaf a | Node (Tree a) (Tree a)
we define the function
tja
:= let tja' (Leaf a) n ls = (0, if n == 0 then a : ls else ls) tja t Node l r) n ls = let (lm, ll) = tja' l (n-1) rl tja' (= tja' r (n-1) ls (rm, rl) in ((lm `min` rm) + 1, ll) = tja' t m [] (m, r) in r
If this code computes something, explain what it computes, maybe with the aid of a small example. If it does not compute anything, explain why this is the case.
For each of these expressions, indicate if they are in WHNF or not. For the ones that are in WHNF, state in one sentence why. For the ones not in WHNF, evaluate them to WHNF or, in case they crash upon evaluation, indicate this.
1 + 5) : succ 4 : map (+1) [1,2] (Just 4) isNothing (-> and b \a b c foldr undefined e [] seq fmap
Implement the Sieve of Eratosthenes for computing prime numbers in Haskell. Recall that the algorithm works as follows. Start from the natural numbers greater than or equal to 2, keep 2 as it is a prime, then strike out all multiples of 2 from the rest of the numbers. The smallest remaining number is also a prime, so keep it. Next, remove all multiples of it from the remaining numbers. Etc.