Skip to content

Instantly share code, notes, and snippets.

@monadplus
Last active May 1, 2021 14:23
Show Gist options
  • Save monadplus/e5d6f330f3d43d57c9a40d3f5f0b23f1 to your computer and use it in GitHub Desktop.
Save monadplus/e5d6f330f3d43d57c9a40d3f5f0b23f1 to your computer and use it in GitHub Desktop.
Laziness in Haskell
import Data.IntMap.Lazy as Map
{-
Notice that the smallest is not evaluated under 'go' function,
otherwise the computation would be ⊥
-}
attachMin :: Ord a => [a] -> [(a, a)]
attachMin l =
let (l', smallest) = go smallest l
in l'
where
go smallest [x] = ([(x, smallest)], x)
go smallest (x:xs) =
let (xs', smallest') = go smallest xs
in ((x, smallest):xs', min x smallest')
-- Data.IntMap.Strict loops
fib :: Int -> IntMap Int
fib n = m
where
m =
Map.fromList $
(1, 1) :
(2, 1) :
[(i, m ! (i -2) + m ! (i -1)) | i <- [3 .. n]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment