Last active
August 29, 2015 14:02
-
-
Save ravinggenius/5503a7ca7b458730bf86 to your computer and use it in GitHub Desktop.
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
class FunctionalArray | |
attr_reader :head | |
attr_reader :tail | |
def initialize(*items) | |
@head = items.first | |
tail = items[1..-1] | |
@tail = (tail.count > 0) ? self.class.new(items[1..-1]) : [] | |
end | |
def count | |
1 + tail.count | |
end | |
def inject(initial, &block) | |
memo = block.call(initial, head) | |
if tail.count > 0 | |
tail.inject(memo, &block) | |
else | |
memo | |
end | |
end | |
def map(&block) | |
reply = inject([]) do |memo, item| | |
[ *memo, block.call(item) ] | |
end | |
self.class.new(reply) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment