Skip to content

Instantly share code, notes, and snippets.

@Veejay
Created April 20, 2012 18:46
Show Gist options
  • Save Veejay/2430981 to your computer and use it in GitHub Desktop.
Save Veejay/2430981 to your computer and use it in GitHub Desktop.
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