Voloaca Octavian
Voloaca Octavian

Reputation: 69

How to do pattern matching in Scheme?

Has anyone an idea how to make pattern matching in Scheme with this two (?x lives-in ?city) (john lives-in new-york) ?

I've tried using match-define, but I didn't succeed.

Upvotes: 5

Views: 6557

Answers (1)

Óscar López
Óscar López

Reputation: 235984

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.

Upvotes: 10

Related Questions