Created
January 18, 2014 12:52
-
-
Save k-tsj/8490031 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
require 'pattern-match' | |
require 'set' | |
module PatternMatch | |
class PatternSetDeconstructor < PatternDeconstructor | |
def initialize(klass, *subpatterns) | |
super(*subpatterns) | |
@klass = klass | |
end | |
def match(vals) | |
super do |val| | |
next false unless val.kind_of?(@klass) | |
members = val.to_a | |
next false unless @subpatterns.length <= members.length | |
members.permutation(@subpatterns.length).find do |perm| | |
perm.zip(@subpatterns).all? {|i, pat| pat.match([i]) } | |
end | |
end | |
end | |
end | |
end | |
def Set.pattern_matcher(*subpatterns) | |
PatternMatch::PatternSetDeconstructor.new(self, *subpatterns) | |
end | |
match(Set[3, 1, 4, 6]) do | |
with(Set.(a, b), guard { a + 5 == b }) do | |
p [a, b] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment