Last active
August 30, 2015 07:21
-
-
Save baweaver/c4ee517fe325d54447c5 to your computer and use it in GitHub Desktop.
Basic functional programming in defining map, reduce, and select.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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