For the excercise on page 25, just type each line into ghci.
Page 39:
#1. The function can only select an element from the list: there's no other way it can obtain a value of type a; in particular, it cannot create new values of this "unknown" type.
Thus, possible valid behaviors include returning the first element, returning the second element, etc.; returning the last element, returning the last-but-one element, etc.; returning the middle element; and so on.
Interestingly, a function with this signature in Haskell cannot return a "random" element from the list, because (for functions with no IO) the same value must be returned every time the function is called with the same input.
#2. Using if:
lastButOne :: [a] -> a
lastButOne (x:xs) = if length xs == 1
then x
else lastButOne xs
With pattern matching (introduced in the following chapter), this can be simplified as:
lastButOne :: [a] -> a lastButOne (x1:[x2]) = x1 lastButOne (x:xs) = lastButOne xs
#3. For either version, trying this on a too-short list (e.g., lastButOne "no") results in the error message "Non-exhaustive patterns in function".
2 comments: