Created
April 20, 2012 18:46
-
-
Save Veejay/2430981 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 Array | |
def extract_options! | |
last.is_a?(::Hash) ? pop : {} | |
end | |
def tail | |
head, *tail = *self | |
tail | |
end | |
def head | |
head, *tail = *self | |
head | |
end | |
def shape | |
head, *tail = *self | |
case | |
when (head.nil? and tail.empty?) | |
:default | |
when tail.empty? | |
:head | |
else | |
:head_tail | |
end | |
end | |
def match(*args) | |
rules = args.extract_options! | |
if rules.has_key?(*args) | |
rules[*args].call | |
else | |
rules[:default].call(*args) | |
end | |
end | |
# About 30 times slower than map though :/ | |
def pmap &block | |
if size > 0 | |
match self.shape, | |
head_tail: lambda{ self.tail.pmap(&block).unshift yield(self.head) }, | |
head: lambda{ [ yield(self.head) ] } | |
else | |
self | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment