Skip to content

Instantly share code, notes, and snippets.

@jcmoyer
Created May 23, 2013 05:45
Show Gist options
  • Select an option

  • Save jcmoyer/5632981 to your computer and use it in GitHub Desktop.

Select an option

Save jcmoyer/5632981 to your computer and use it in GitHub Desktop.
String-lambdas with syntax inspired by OCaml/F#
-- taken from http://lua-users.org/wiki/StringTrim
function trim(s)
return s:match "^%s*(.-)%s*$"
end
-- creates a function from a lambda string
function fun(text)
-- divide the text into arg list and return body
local a, r = text:match("(.-)->(.*)")
a = trim(a)
r = trim(r)
-- we use a local, named function so that lambdas can recursively call themselves
local src = string.format([[-- %s
local function fun(%s) return (%s) end
return fun
]],
text, a:gsub('%s+', ','), r)
return assert(loadstring(src))()
end
-- recursive factorial lambda
factorial = fun[[a s -> a > 0 and fun(a - 1, (s or 1) * a) or (s or 1)]]
-- maps a function over an array table
function map(f, t)
local r = {}
for i = 1, #t do
r[i] = f(t[i])
end
return r
end
-- problem: lambdas can currently only access data declared in the global scope
local results = map(fun[[a -> factorial(a)]], {1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
print(unpack(results))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment