Created
February 10, 2012 02:38
-
-
Save soutaro/1785761 to your computer and use it in GitHub Desktop.
Testing structures with meta variables, as unification.
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
# Testing two structures if they are unifiable. | |
# | |
module UnifierAssertion | |
def unify(es, s = {}, &block) | |
return s if es.empty? | |
e = es.shift | |
a,b = e | |
a = s[a] || a | |
b = s[b] || b | |
if Hash === a and Hash === b | |
if block_given? | |
yield a.keys.sort, b.keys.sort | |
else | |
return nil unless a.keys.sort == b.keys.sort | |
end | |
a.keys.each do |key| | |
es << [a[key], b[key]] | |
end | |
elsif Array === a and Array === b | |
es += a.zip(b) | |
elsif Symbol === a and a.to_s =~ /^'/ | |
s = self.subst(s, a, b).merge!(a => b) | |
elsif Symbol === b and b.to_s =~ /^'/ | |
s = self.subst(s, b, a).merge!(b => a) | |
else | |
p a,b | |
if block_given? | |
yield a, b | |
else | |
return nil unless a == b | |
end | |
end | |
unify(es, s, &block) | |
end | |
# Substitute any occurance of x in hash to y. | |
# ie compute hash[x -> y] | |
def subst(hash, x, y) | |
result = {} | |
hash.each do |key, value| | |
if key == x | |
key = y | |
end | |
if value == x | |
value = y | |
end | |
result[key] = value | |
end | |
end | |
def assert_unify(a, b, message = "") | |
self.unify([[a, b]]) do |x, y| | |
assert_equal x, y, message | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment