Skip to content

Instantly share code, notes, and snippets.

@andrewthad
Created June 14, 2023 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewthad/5308154742a9a3c29a78b156c93442ea to your computer and use it in GitHub Desktop.
Save andrewthad/5308154742a9a3c29a78b156c93442ea to your computer and use it in GitHub Desktop.
Examples of folds and strict folds
{-# language BangPatterns #-}
main :: IO ()
main = print (createMap myList)
myList :: [String]
myList = ["foo","bar","foo","bar"]
-- updateMap :: Map String Int -> String -> Map String Int
-- updateMap v k = Map.updateWith (+1) k m
--
-- createMap :: [String] -> Map String Int
-- createMap keys = foldl' updateMap Map.empty keys
-- createMap :: [String] -> Map String Int
-- createMap keys = foldl'
-- (\acc key -> Map.updateWith (+1) key acc
-- ) Map.empty keys
createMap :: Map String Int -> [String] -> Map String Int
createMap !acc [] = acc
createMap !acc (x : xs) = Map.insertWith (+1) x 1 acc
myFunction :: Int -> Int -> Foo
myFunction !x !y = _
sum :: [Int] -> Int
sum [] = 0
sum (x : xs) = x + sum xs
sum [42,37,58,12]
==>
42 + sum [37,58,12]
==>
37 + sum [58,12]
==>
58 + sum [12]
==>
12 + sum []
==>
0
foo =
... do some stuff
x = ...
return (bar(x))
sum :: Int -> [Int] -> Int
sum acc [] = acc
sum acc (x : xs) =
let y = x + acc
in sum y xs
sum 0 [42,37,58,12]
==>
sum <42 + 0> [37,58,12]
sum <37 + <42 + 0>> [58,12]
sum <58 + <37 + <42 + 0>>> [12]
sum <12 + <58 + <37 + <42 + 0>>>> []
<12 + <58 + <37 + <42 + 0>>>>
... stack frame thing again
sum :: Int -> [Int] -> Int
sum !acc [] = acc
sum !acc (x : xs) =
let y = x + acc
in sum y xs
sum 0 [42,37,58,12]
==>
sum <42 + 0> [37,58,12]
sum <42> [37,58,12]
sum <37 + 42> [58,12]
sum <79> [58,12]
data Person = Person
{ name :: String
, age :: Int
}
p = <thunk>
p = Person{name=<thunk>, age=<thunk>}
p = Person{name="barb", age=20}
(\x -> x + x + y)
possibleAge :: Bool -> Person -> Int
possibleAge b !p = case b of
True -> p.age
False -> 0
possibleAge False undefined ==> 0
possibleAge False undefined ==> undefined
...
case possibleAge myBool myPerson of
42 ->
1 ->
_ ->
-- foldl' :: (b -> a -> b) -> b -> [a] -> b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment