Skip to content

Instantly share code, notes, and snippets.

@DaQuirm
Created December 21, 2018 11:35
Show Gist options
  • Save DaQuirm/8e2494e76185ac81911e54e3d6ef4544 to your computer and use it in GitHub Desktop.
Save DaQuirm/8e2494e76185ac81911e54e3d6ef4544 to your computer and use it in GitHub Desktop.
-- foldl using only foldr & lambdas
-- increase every number in a list by one except when it's not preceded by one
-- e.g. inc [1, 2, 1, 3, 4, 5] == [2, 2, 2, 3, 5, 6]
-- folding function
folder :: ([Int], Int) -> Int -> ([Int], Int)
folder (acc, u) item = (acc ++ [item + u], if item == 1 then 0 else 1)
-- initial acc value
initAcc :: ([Int], Int)
initAcc = ([], 1)
-- inc using native foldl
inc :: [Int] -> [Int]
inc = fst . foldl folder initAcc
-- inc using foldr-based foldl
inc' :: [Int] -> [Int]
inc' = fst . foldlE folder initAcc
where foldlE f z xs = foldr (\item fs -> fs . (`f` item)) id xs z
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment