私は2つの機能を持ってい apply_rule
ますmatch
. それぞれが独立して定義されており、どのクラスにも属していません。
match
は、2 つの必須パラメーターと、オプションのパラメーター を受け取りますpairs
。デフォルトは空の辞書です。以下は と のコードapply_rule
ですmatch
。match
が呼び出され、オプションのパラメーターが指定されていないことに注意してくださいpairs
。
def apply_rule(pat, rule):
if not isrule(rule):
return "Not a valid rule"
subs = match(lhs(rule), pat)
if subs == {}:
return pat
else:
return substitute(rhs(rule), subs)
def match(pat, lst, pairs={}):
if pat == [] and lst == []:
return pairs
elif isvariable(pat[0]):
if pat[0] not in pairs.keys():
pairs[pat[0]] = lst[0]
elif pat[0] in pairs.keys() and lst[0] != pairs[pat[0]]:
return False
elif pat[0] != lst[0]:
return False
return match(pat[1:], lst[1:], pairs)
のテストで定義されているように、 を「記憶」しているため、現在、 の単体テストはmatch
失敗します。pairs
apply_rule
ただし、3 行目を に変更するとapply_rule
、subs = match(lhs(rule), pat, {})
テストはパスします。なぜなのかご存知ですか?私が知る限り、 from が他のテストで呼び出されたときmatch
の値を記憶する方法はありません。pairs
以下は、参照用の単体テストです。
def test_match(self):
self.assertEqual({}, match(['a', 'b', 'c'], ['a', 'b', 'c']))
self.assertEqual(self.dict_with_x, match(['a', '_X', 'c'], ['a', '5', 'c']))
self.assertEqual(self.dict_with_x, match(self.pat_with_xx, self.list_with_55))
self.assertEqual(self.dict_with_xy, match(self.pat_with_xy, self.list_with_5hi))
self.assertFalse(match(self.pat_with_xx, ['a', 'b', 'c', 'd']))
self.assertFalse(match(['a', 'b', 'c'], ['a', 'b', 'd']))
def test_apply_and_firerule(self):
pattern1 = "my mother thinks I am fat".split(' ')
expected = "do you think you are fat ?".split(' ')
self.assertEqual(apply_rule(pattern1, self.r1), expected)
そして失敗のメッセージ…
Traceback (most recent call last):
File "pattern_matcher_tests.py", line 65, in test_match
self.assertEqual({}, match(['a', 'b', 'c'], ['a', 'b', 'c']))
AssertionError: {} != {'_Y': 'fat', '_X': 'mother'}
- {}
+ {'_X': 'mother', '_Y': 'fat'}