algorithm-design-with-haskell/ch01.lhs

39 lines
933 B
Text
Raw Normal View History

2021-01-28 07:58:59 +00:00
Chapter 1: Functional Programming
===
Exercise 1.2
---
Trawling through Data.List we discovered the function
> uncons :: [a] -> Maybe (a, [a])
of whose existence we were quite unconscious. Guess the definition of uncons.
> uncons [] = Nothing
> uncons (hd : tl) = Just (hd, tl)
Exercise 1.3
---
The library Data.List does not provide functions
> wrap :: a -> [a]
> unwrap :: [a] -> a
> single :: [a] -> Bool
for wrapping a value into a singleton list, unwrapping a singleton list into
its sole occupant, and testing a list for being a singleton. This is a pity,
for the three functions can be very useful on occasions and will appear a
number of times in the rest of this book. Give appropriate definitions.
> -- return should work here too
> wrap x = [x]
>
> -- TBH unwrap should be returning Maybe since otherwise this throws an
> -- exception on unmatched cases
> unwrap [x] = x
>
> single [x] = True
> single _ = False