有谁知道如何在 Scheme 中使用这两个 (?x lives-in ?city) (john living-in new-york) 进行模式匹配?
我试过使用匹配定义,但没有成功。
有谁知道如何在 Scheme 中使用这两个 (?x lives-in ?city) (john living-in new-york) 进行模式匹配?
我试过使用匹配定义,但没有成功。
I guess you meant pattern matching. For the general solution to this problem, think about implementing the Unification Algorithm, there's a complete working solution described in SICP. Alternatively, consider embedding miniKANREN in your code, it's a simple logic programming system that works with Scheme.
Now, for a simpler match you can use Racket's Pattern Matching abilities. For the example in the question:
(define expression '(john lives-in new-york))
(match expression
[(list ?x 'lives-in ?city) (list ?x ?city)]
[_ #f])
=> '(john new-york)
The above will match a given expression against the (?x lives-in ?city)
pattern, returning a list with the matched values for ?x
and ?city
, or #f
if no match was found.