Skip to content
This repository has been archived by the owner on Dec 5, 2019. It is now read-only.

Commit

Permalink
Implemented functional.head, functional.tail, and functional.decons (…
Browse files Browse the repository at this point in the history
…which splits a list into both its head and tail)
  • Loading branch information
jspahrsummers committed Oct 10, 2011
1 parent 003bef6 commit 6f473e7
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
39 changes: 39 additions & 0 deletions functional.lua
Expand Up @@ -193,6 +193,45 @@ module.flatten = function (list)
return result
end

-- Returns the first element from 'list', or nil if the list is empty.
module.head = function (list)
if not list or # list == 0 then
return nil
else
return list[1]
end
end

-- Returns all but the first element from 'list'. If 'list' only contains one element, returns an empty list. If 'list' is empty, returns nil.
module.tail = function (list)
local head, tail = module.decons(list)

if head == nil then
return nil
else
return tail
end
end

-- Returns the head and the tail of 'list', or nil if the list is empty.
module.decons = function (list)
if not list then
return nil
end

local count = # list
if count == 0 then
return nil
end

local tail = {}
for i = 2, count do
tail[i - 1] = list[i]
end

return list[1], tail
end

-- Sandbox and export the functions in this module under a 'functional' namespace
functional = module.map_pairs(module, function (name, func)
return name, pure.sandbox(func)
Expand Down
3 changes: 3 additions & 0 deletions main.lua
Expand Up @@ -69,3 +69,6 @@ print(h(3, 6))

print(util.table_tostring(functional.flatten({ { 5 }, {{{{ "hello" }}}}, {{ "bar" }} })))

local tbl = { "foo", 2, 3, "bar", 5.5 }
print(tostring(functional.head(tbl)))
print(util.table_tostring(functional.tail(tbl)))

0 comments on commit 6f473e7

Please sign in to comment.