1 ! Copyright (C) 2006 Chris Double.
2 ! See http://factorcode.org/license.txt for BSD license.
4 ! Based on pattern matching code from Paul Graham's book 'On Lisp'.
5 USING: parser kernel words namespaces sequences tuples
11 : define-match-var ( name -- )
13 dup t "match-var" set-word-prop
14 dup [ get ] curry define-compound ;
16 : define-match-vars ( seq -- )
17 [ define-match-var ] each ;
19 : MATCH-VARS: ! vars ...
20 ";" parse-tokens define-match-vars ; parsing
22 : match-var? ( symbol -- bool )
23 dup word? [ "match-var" word-prop ] [ drop f ] if ;
25 : (match) ( value1 value2 -- matched? )
27 { [ dup match-var? ] [ set t ] }
28 { [ over match-var? ] [ swap set t ] }
29 { [ 2dup = ] [ 2drop t ] }
30 { [ 2dup [ _ eq? ] either? ] [ 2drop t ] }
31 { [ 2dup [ sequence? ] both? ] [
32 2dup [ length ] 2apply =
33 [ [ (match) ] 2all? ] [ 2drop f ] if ] }
34 { [ 2dup [ tuple? ] both? ]
35 [ [ tuple>array ] 2apply [ (match) ] 2all? ] }
39 : match ( value1 value2 -- bindings )
40 [ (match) ] H{ } make-assoc swap [ drop f ] unless ;
42 MACRO: match-cond ( assoc -- )
44 [ "Fall-through in match-cond" throw ]
47 >r [ dupd match ] curry r>
52 : replace-patterns ( object -- result )
54 { [ dup match-var? ] [ get ] }
55 { [ dup sequence? ] [ [ replace-patterns ] map ] }
56 { [ dup tuple? ] [ tuple>array replace-patterns >tuple ] }
60 : match-replace ( object pattern1 pattern2 -- result )
61 -rot match [ replace-patterns ] bind ;