A pattern match macro for chez-scheme

701 views
Skip to first unread message

ra...@openmailbox.org

unread,
Nov 11, 2016, 3:49:21 PM11/11/16
to chez-...@googlegroups.com
Hello!


Here is a pattern match macro for chez-scheme:

* https://github.com/rain-1/chez-match/tree/master


You can use it like this:

~/Code/chez-match$ CHEZSCHEMELIBDIRS=. scheme
Chez Scheme Version 9.4.1
Copyright 1984-2016 Cisco Systems, Inc.

> (import (match))
> (match '(foo (bar))
((foo) 'a)
((foo (bar)) 'b)
((foo (baz)) 'c)
((foo y) (list '? y)))
b
> (match '(foo (quux))
((foo) 'a)
((foo (bar)) 'b)
((foo (baz)) 'c)
((foo y) (list '? y)))
(? (quux))
>


It works by compiling each pattern into a list of instructions, merging
those instructions into a tree, then using a syntax-rule to transform
that instruction tree into scheme code that implements the matching
rules.

If you notice any bugs with it please feel free to report them to me!
You're also welcome to fork it and change the pattern language (or
anything else about it).

happy hacking!

Atticus

unread,
Nov 13, 2016, 9:09:40 AM11/13/16
to ra...@openmailbox.org, chez-...@googlegroups.com

ra...@openmailbox.org

unread,
Nov 18, 2016, 6:31:46 PM11/18/16
to chez-...@googlegroups.com
Here is a linear matcher. It doesn't optimize by sharing work between
rows - but the pattern language is extensible. The main use of this is
to add record-matching:

https://github.com/rain-1/chez-match/blob/master/el-match.scm

(import (rename (chezscheme)
(define-record %define-record))
(match))

;; redefine define-record so that we get nicer printing
(define-syntax define-record
(syntax-rules ()
((define-record <name> (<field> ...))
(begin (%define-record <name> (<field> ...))
(define-record-matcher <name> (<field> ...))
(record-reader '<name> (type-descriptor <name>))))))

In order to use it you do have to call some function from inside the
module
<https://github.com/cisco/ChezScheme/issues/116>. Doing this seems to
work inside a module:

(define-syntax %foo
(begin (foo)
(lambda (stx) stx)))

Here's an example of use:

> (import (match) (modified-define-record))
> (define-record kons (kar kdr))
> (match (make-kons 1 2) ((kons x y) (list y x)))
(2 1)

> (match (make-kons 1 2) ((kons '1 y) (list y)))
Exception in match-pats: no expander for pattern with irritant (quote 1)
Type (debug) to enter the debugger.
> (foo)
#t
> (match (make-kons 1 2) ((kons '1 y) (list y)))
(2)

I welcome any criticism or review of the code.
Reply all
Reply to author
Forward
0 new messages