O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required