Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Folding Cheat Sheet #5

Folding Cheat Sheet #5

Folding a list right and left using Cons and Nil results in the identity and reverse functions.

Keywords: cons, folding, identity function, left fold, nil, reverse function, right fold.

Avatar for Philip Schwarz

Philip Schwarz

June 23, 2024
Tweet

More Decks by Philip Schwarz

Other Decks in Programming

Transcript

  1. CHEAT-SHEET Folding #5 ∶ / \ 𝒂𝟎 ∶ / \

    𝒂𝟏 ∶ / \ 𝒂𝟐 ∶ / \ 𝒂𝟑 𝒇 / \ 𝒂𝟎 𝒇 / \ 𝒂𝟏 𝒇 / \ 𝒂𝟐 𝒇 / \ 𝒂𝟑 𝒆 @philip_schwarz slides by https://fpilluminated.com/
  2. ∶ / \ 𝑥1 ∶ / \ 𝑥2 ∶ /

    \ 𝑥3 ∶ / \ 𝑥4 ‥ / \ ‥ 𝑥4 / \ ‥ 𝑥3 / \ ‥ 𝑥2 / \ [ ] 𝑥1 ∶ / \ 𝑥4 ∶ / \ 𝑥3 ∶ / \ 𝑥2 ∶ / \ 𝑥1 𝑥4 ∶ (𝑥3 ∶ 𝑥2 ∶ 𝑥1 ∶ ) ∶ / \ 𝑥1 ∶ / \ 𝑥2 ∶ / \ 𝑥3 ∶ / \ 𝑥4 𝑥1 : (𝑥2 : 𝑥3 : 𝑥4 : ) (( ‥𝑥1 ‥𝑥2 )‥𝑥3 )‥𝑥4 var acc = [ ] foreach(x in xs) acc = acc ‥x) return acc 𝑓𝑜𝑙𝑑𝑟 ∶ 𝑥𝑠 𝑓𝑜𝑙𝑑𝑙 ‥ 𝑥𝑠 𝑥𝑠 = [𝑥1 , 𝑥2 , 𝑥3 , 𝑥4 ] 𝑓𝑜𝑙𝑑𝑟 ∶ = 𝑖𝑑𝑒𝑛𝑡𝑖𝑡𝑦 = 𝑓𝑜𝑙𝑑𝑟 λ𝑥. λ𝑦. 𝑥 ∶ 𝑦 𝑓𝑜𝑙𝑑𝑙 ‥ = 𝑟𝑒𝑣𝑒𝑟𝑠𝑒 = 𝑓𝑜𝑙𝑑𝑙 λ𝑥. λ𝑦. 𝑦 ∶ 𝑥 𝑓𝑜𝑙𝑑𝑟 ∷ 𝛼 → 𝛽 → 𝛽 → 𝛽 → 𝛼 → 𝛽 𝑓𝑜𝑙𝑑𝑟 𝑓 𝑒 = 𝑒 𝑓𝑜𝑙𝑑𝑟 𝑓 𝑒 𝑥: 𝑥𝑠 = 𝑓 𝑥 𝑓𝑜𝑙𝑑𝑟 𝑓 𝑒 𝑥𝑠 𝑓𝑜𝑙𝑑𝑙 ∷ 𝛽 → 𝛼 → 𝛽 → 𝛽 → 𝛼 → 𝛽 𝑓𝑜𝑙𝑑𝑙 𝑓 𝑒 = 𝑒 𝑓𝑜𝑙𝑑𝑙 𝑓 𝑒 𝑥: 𝑥𝑠 = 𝑓𝑜𝑙𝑑𝑙 𝑓 𝑓 𝑒 𝑥 𝑥𝑠 ∶ = λ𝑥. λ𝑦. 𝑥 ∶ 𝑦 ‥ = λ𝑥. λ𝑦. 𝑦 ∶ 𝑥 ‥ = 𝑓𝑙𝑖𝑝 ∶ 𝑤ℎ𝑒𝑟𝑒 𝑓𝑙𝑖𝑝 𝑓 𝑥 𝑦 = 𝑓 𝑦 𝑥 ∶ / \ ℎ 𝑡 . . / \ 𝑡 ℎ equivalent to [𝑥4 , 𝑥3 , 𝑥2 , 𝑥1 ] 𝑖𝑑𝑒𝑛𝑡𝑖𝑡𝑦 𝑟𝑒𝑣𝑒𝑟𝑠𝑒 [𝑥1 , 𝑥2 , 𝑥3 , 𝑥4 ] > id = foldr (:) [] > rev = foldl (flip (:)) [] > id [1,2,3,4] [1,2,3,4] > rev [1,2,3,4] [4,3,2,1] > id = foldr (\x y -> x:y) [] > rev = foldl (\x y -> y:x) [] > id [1,2,3,4] [1,2,3,4] > rev [1,2,3,4] [4,3,2,1] 𝑟𝑒𝑝𝑙𝑎𝑐𝑒: ∶ 𝑤𝑖𝑡ℎ ∶ 𝑤𝑖𝑡ℎ 𝑟𝑒𝑝𝑙𝑎𝑐𝑒: ∶ 𝑤𝑖𝑡ℎ 𝑓 𝑤𝑖𝑡ℎ 𝑒 var acc = e foreach(x in xs) acc = f (acc, x) return acc folding a list right and left using Cons and Nil results in the identity and reverse functions