Real World Haskell – Exercises Chapter 4

My answers to the exercises of the fourth chapter.

Page 84:

1. Write your own “safe” definitions of the standard partial list functions, but make sure they never fail.

safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead xs = Just (head xs)

safeTail :: [a] -> Maybe [a]
safeTail [] = Nothing
safeTail xs = Just (tail xs)

safeLast :: [a] -> Maybe a
safeLast [] = Nothing
safeLast xs = Just (last xs)

safeInit :: [a] -> Maybe [a]
safeInit [] = Nothing
safeInit xs = Just (init xs)

2. Write a function splitWith that acts similarly to words but takes a predicate and a list of any type, and then splits its input list on every element for which the predicate returns False.

splitWith :: (a -> Bool) -> [a] -> [[a]]
splitWith p xs =
  let (pre,suf) = break p xs
      suf' = dropWhile p suf
  in pre : case suf' of
             [] -> []
             _  -> splitWith p suf'

Page 97:

1. Use a fold (choosing the appropriate fold will make your code much simpler) to rewrite and improve upon the asInt function from the section called “Explicit recursion” on page 85.

import Data.Char (digitToInt)
import Data.List (foldl')

asInt_fold :: String -> Int
asInt_fold ('-':xs) = -1 * asInt_fold xs
asInt_fold xs       = foldl' step 0 xs
  where
    step :: Int -> Char -> Int
    step x y = 10 * x + digitToInt y

6. Write your own definition of concat using foldr.

myConcat = foldr (++) []

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 0W2fkW to the field below: