Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 642
Voloaca Octavian Avatar asked Apr 05 '13 09:04

Voloaca Octavian


1 Answers

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.

like image 179
Óscar López Avatar answered Oct 15 '22 23:10

Óscar López