Real World Haskell – Exercises Chapter 2

My answers to the exercises of the second chapter.

Page 25:

1. What are the types of the following expressions?

False :: Bool
(["foo", "bar"], 'a') :: ([String], Char)
[(True, []), (False, [['a']])] :: [(Bool,[[Char]])]

Page 39:

1. Haskell provides a standard function, last :: [a] -> a, that returns the last element of a list. From reading the type alone, what are the possible valid behaviors (omitting crashes and infinite loops) that this function could have?

From the type alone there is no way to find out what the real type is, neither is there a way to manipulate a value of that type, thus the “only” thing the code can do is return an element of the list.

What are a few things that this function clearly cannot do?

  • Return the size of the list.
  • Reverse the list.

2. Write a function, lastButOne, that returns the element before the last.

lastButOne = head . tail . reverse

Load your lastButOne function into ghci and try it out on lists of different lengths. What happens when you pass it a list that’s too short?

Prelude> lastButOne "a"
*** Exception: Prelude.head: empty list

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please copy the string RantUn to the field below: