Building with Functional Primitives

We had to define our own map() earlier, which we’ll use again in a minute. Let’s define a few more functional primitives that we can arrange into bigger and better things:

 function each (things, fn)
  for i, thing in ipairs(things) do
  fn(thing)
  end
 end
 function filter (things, fn)
  local filtered = {}
  each(things, function(thing)
  if fn(thing) then
  table.insert(filtered, thing)
  end
  end)
  return filtered
 end
 function cons (things, ...)
  local all = {}
  each({...}, function(t)
  table.insert(all, t)
  end)
  each(things, function(t)
  table.insert(all, t)
  end)
  return all
 end

I should point out that all of these are relatively slow, because they copy elements between Lua tables. We ...

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.