Skip to content

Instantly share code, notes, and snippets.

@baweaver
Last active August 30, 2015 07:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baweaver/c4ee517fe325d54447c5 to your computer and use it in GitHub Desktop.
Save baweaver/c4ee517fe325d54447c5 to your computer and use it in GitHub Desktop.
Basic functional programming in defining map, reduce, and select.
# Do note I'm being very purposely verbose on some of these for the sake of clarity
map = -> list, fn {
if list.empty?
[]
else
head, *tail = list
[fn.call(head)].concat map.call(tail, fn)
end
}
# [3] pry(main)> map.call([1,2,3], -> x { x * 2 })
# => [2, 4, 6]
reduce = -> list, fn, accumulator = nil {
if list.empty?
accumulator
else
head, *tail = list
reduce.call(tail, fn, fn.call(accumulator, head))
end
}
# [5] pry(main)> reduce.call([1,2,3], -> acc, i { acc + i }, 0)
# => 6
select = -> list, fn {
if list.empty?
[]
else
head, *tail = list
(fn.call(head) ? [head] : []).concat(select.call(tail, fn))
end
}
# [7] pry(main)> select.call([1,2,3], -> i { i.even? })
# => [2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment