Skip to content

Commit

Permalink
Add foldl example
Browse files Browse the repository at this point in the history
  • Loading branch information
arkt8 committed Feb 28, 2023
1 parent fa0fba1 commit 722d369
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
/lua_modules
/.luarocks
/.out
/.ccls*
/tree
**.o
**.so
18 changes: 18 additions & 0 deletions lua/functional/foldl.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
-- This is equivalent to the Haskell foldl:
-- foldl :: (b -> a -> b) -> b -> [a] -> b
-- foldl f z [] = z
-- foldl f z (x:xs) = foldl f (f z x) xs



local foldl
function foldl(f, z, xs, i)
if (i or 0) >= #xs then return z end
i = (i or 0) + 1
return foldl(f, f(z, xs[i]), xs, i)
end

local sum
function sum(a, b) return a + b end

print( assert( foldl(sum,0,{1,2,3,5,8,13,21,34,55,89}) == 231 ) )

0 comments on commit 722d369

Please sign in to comment.