Posted By


rtperson on 06/01/11

Tagged


Statistics


Viewed 682 times
Favorited by 0 user(s)

Real World Haskell Exercise - Ch 4, Ex 2-4


/ Published in: Haskell
Save to your folder(s)

I'm posting the rest of these, mostly because I'm still patting myself on the back for my point-free implementation of exercise 3, and because I give myself about two months before I entirely forget how I did it...


Copy this code and paste it in your HTML
  1. import Data.Char (digitToInt) -- we'll need ord
  2. import Data.List (foldl')
  3.  
  4.  
  5.  
  6.  
  7. {- Ex 2: The asInt_fold function uses error, so its
  8.   callers cannot handle errors. Rewrite it to
  9.   fix this problem.
  10. -}
  11. type ErrorMessage = String
  12. asInt_either :: String -> Either ErrorMessage Int
  13. asInt_either [] = Left "String is empty"
  14. asInt_either "-" = Left "dash is not a number"
  15. asInt_either ('-':xs) = Right $ (-1) * asInt_fold xs
  16. asInt_either str = Right $ asInt_fold str
  17.  
  18. {- Ex 3: The Prelude function concat
  19.   concatenates a list of lists into a single list,
  20.   and has the following type.
  21.  
  22.   concat :: [[a]] -> [a]
  23.  
  24.   Write your own definition of concat using foldr.
  25. -}
  26.  
  27. list1 = [1,2,3,4,5]
  28. list2 = [6,7,8,9,10]
  29. list3 = [11,12,13,14,15]
  30. list4 = [16,17,18,19,20]
  31. listA = [list1, list2, list3, list4]
  32.  
  33. -- this was easy...
  34. concat_foldr :: [[a]] -> [a]
  35. concat_foldr = foldr (++) []
  36.  
  37. {- Ex 4: Write your own definition of the standard takeWhile
  38.   function, first using explicit recursion, then foldr.
  39.  
  40.   (I assume 2 separate functions...)
  41.  
  42.   --- test cases (from the Prelude comments)
  43.   takeWhile (< 3) [1,2,3,4,1,2,3,4] == [1,2]
  44.   takeWhile (< 9) [1,2,3] == [1,2,3]
  45.   takeWhile (< 0) [1,2,3] == []
  46.  
  47. -}
  48.  
  49. takeWhile_rec :: (a -> Bool) -> [a] -> [a]
  50. takeWhile_rec _ [] = []
  51. takeWhile_rec p (x:xs)
  52. | p x = x : takeWhile_rec p xs
  53. | otherwise = []
  54.  
  55. takeWhile_foldr :: (a -> Bool) -> [a] -> [a]
  56. takeWhile_foldr p = foldr (\x xs -> if p x then x:xs else []) []
  57.  
  58. dropWhile_foldr :: (a -> Bool) -> [a] -> [a]
  59. dropWhile_foldr p = foldr (\x xs -> if p x then xs else x:xs) []

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.