Real World Haskell - 第4章 Exercises Part2

Real World HaskellHaskell を継続的に勉強中。


Chapter 4. Functional programming
Chapter 4. Functional programming

回答は順次追記していく。
Excercise が溜まってきたので消化しないと・・・

Excercises (Section "Left folds, laziness, and space leaks" の後にあるもの)

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”.

-- file: ch04/ch04.exercises.hs
asInt_fold :: String -> Int

Your function should behave as follows.

ghci> asInt_fold "101"
101
ghci> asInt_fold "-31337"
-31337
ghci> asInt_fold "1798"
1798

Extend your function to handle the following kinds of exceptional conditions by calling error.

ghci> asInt_fold ""
0
ghci> asInt_fold "-"
0
ghci> asInt_fold "-3"
-3
ghci> asInt_fold "2.7"
*** Exception: Char.digitToInt: not a digit '.'
ghci> asInt_fold "314159265358979323846"
564616105916946374


2. The asInt_fold function uses error, so its callers cannot handle errors. Rewrite it to fix this problem.

-- file: ch04/ch04.exercises.hs
type ErrorMessage = String
asInt_either :: String -> Either ErrorMessage Int
ghci> asInt_either "33"
Right 33
ghci> asInt_either "foo"
Left "non-digit 'o'"


3. The Prelude function concat concatenates a list of lists into a single list, and has the following type.

-- file: ch04/ch04.exercises.hs
concat :: [[a]] -> [a]

Write your own definition of concat using foldr.


4. Write your own definition of the standard takeWhile function, first using explicit recursion, then foldr.


5. The Data.List module defines a function, groupBy, which has the following type.

-- file: ch04/ch04.exercises.hs
groupBy :: (a -> a -> Bool) -> [a] -> [[a]]


Use ghci to load the Data.List module and figure out what groupBy does, then write your own implementation using a fold.


6. How many of the following Prelude functions can you rewrite using list folds?

* any
* cycle
* words
* unlines

For those functions where you can use either foldl' or foldr, which is more appropriate in each case?

1