Skip to content

Latest commit

 

History

History
142 lines (135 loc) · 2.33 KB

ch10.adoc

File metadata and controls

142 lines (135 loc) · 2.33 KB

10 Folding lists

10.5 Fold left

Intermission: Exercises

  1. b) and c) have the same result, a) has error

    foldr (*) 1 [1..5]
    -- b)
    foldl (flip (*)) 1 [1..5]
    -- c)
    foldl (*) 1 [1..5]
  2. evaluation steps of foldl (flip (*)) 1 [1..3]

    foldl (flip (*)) 1 [1..3]
     = foldl (flip (*)) (1 * 1) [2,3]
     = foldl (flip (*)) (2 * (1 * 1)) [3]
     = foldl (flip (*)) (3 * (2 * (1 * 1))) []
     = (3 * (2 * (1 * 1)))
  3. c) one difference between foldr and foldl is that foldr, but not foldl, associates to the right

  4. a) folds are catamorphisms, they are used to reduce structure

  5. fixed functions

    1. foldr (++) "" ["woot", "WOOT", "woot"]

    2. foldr max "" ["fear","is","the","little","death"]

    3. foldr (&&) True [False, True]

    4. foldr (||) True [False, True] always return True

    5. foldl (\x y → x ++ show y) "" [1..5]

    6. foldr (flip const) 'a' [1..5]

    7. foldr (flip const) 0 "tacos"

    8. foldl const 0 "burritos"

    9. foldl const 'z' [1..5]

10.6 How to write fold functions

Intermission: Exercises

link:ch10_10.6_0.hs[role=include]

10.9 Scans

The fibs using scanl is a little bit of a mind bender at the beginning. I wrote out the evaluation https://gist.github.com/lukleh/67cf0a78205d3f6bd2d9

link:ch10_10.9_0.hs[role=include]

10.10 Chapter Exercises

Warm-up and review

  1. tuples

    link:ch10_10.10_0.hs[role=include]
  2. following function return average size (round to integer) of word in a sentece (string)

    link:ch10_10.10_1.hs[role=include]
  3. returing Fractional values

    link:ch10_10.10_2.hs[role=include]

Rewriting functions using folds

  1. myOr

    myOr :: [Bool] -> Bool
    myOr = foldr (||) False
  2. myAny

    link:ch10_10.10_3.hs[role=include]
  3. myElem

    link:ch10_10.10_4.hs[role=include]
  4. myReverse

    link:ch10_10.10_5.hs[role=include]
  5. myMap

    link:ch10_10.10_6.hs[role=include]
  6. myFilter

    link:ch10_10.10_7.hs[role=include]
  7. squish

    link:ch10_10.10_8.hs[role=include]
  8. squishMap

    link:ch10_10.10_9.hs[role=include]
  9. squishAgain using squishMap

    link:ch10_10.10_10.hs[role=include]
  10. myMaximumBy

    link:ch10_10.10_11.hs[role=include]
  11. myMinimumBy

    link:ch10_10.10_12.hs[role=include]