typeclasses / haskell-phrasebook

The Haskell Phrasebook: a quick intro to Haskell via small annotated example programs
https://typeclasses.com/phrasebook
210 stars 22 forks source link

Create fold.hs #20

Closed gutierrezje closed 4 years ago

gutierrezje commented 5 years ago

Explaining folds with strings and a simple sum example

chris-martin commented 5 years ago

I like it. So we've been going back and forth extensively on which fold primitives are the right ones to introduce, and although I said initially that I wanted to use foldl', we've settled on foldr and foldMap as the basics in the interest of giving a minimal recommendation of essential folding functions to learn. Here's our revisions:

import Data.Foldable (foldr, foldMap)
import Prelude hiding (sum)

sum :: [Integer] -> Integer
sum = foldr (+) 0

commaList :: [String] -> String
commaList = foldr commaSep ""
  where
    commaSep x phrase =
        x ++ (if null phrase then "" else (", " ++ phrase))

bulletList :: [String] -> String
bulletList xs = foldMap bulletItem xs
  where
    bulletItem x = "  - " ++ x ++ "\n"

main =
  do
    let numbers = [1 .. 5]
    putStrLn (show numbers)
    putStrLn (show (sum numbers))

    let words = ["One", "Two", "Three", "Four", "Five"]
    putStrLn (commaList words)
    putStr (bulletList words)

We changed the foldMapStrings example to bulletList to try to contrast the comma-list example with something that foldMap is really appropriate for.

This'll be released under the creative commons CC BY-NC 4.0 license - Please let us know if that's okay and how you'd like to be attributed.

gutierrezje commented 5 years ago

Looks great, glad I could help somewhat! The license is good and as for credit, a link to my Github, just my name and username, or whatever else seems appropriate is fine.

chris-martin commented 4 years ago

Merged and annotated! https://typeclasses.com/phrasebook/folding-lists