better invocation documentation
[bpt/guile.git] / module / system / base / pmatch.scm
1 ;;; pmatch, a simple matcher
2
3 ;;; Copyright (C) 2009, 2010 Free Software Foundation, Inc
4 ;;; Copyright (C) 2005,2006,2007 Oleg Kiselyov
5 ;;; Copyright (C) 2007 Daniel P. Friedman
6 ;;;
7 ;;; This library is free software; you can redistribute it and/or
8 ;;; modify it under the terms of the GNU Lesser General Public
9 ;;; License as published by the Free Software Foundation; either
10 ;;; version 3 of the License, or (at your option) any later version.
11 ;;;
12 ;;; This library is distributed in the hope that it will be useful,
13 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 ;;; Lesser General Public License for more details.
16 ;;;
17 ;;; You should have received a copy of the GNU Lesser General Public
18 ;;; License along with this library; if not, write to the Free Software
19 ;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
21 ;;; Originally written by Oleg Kiselyov for LeanTAP in Kanren, which is
22 ;;; available under the MIT license.
23 ;;;
24 ;;; http://kanren.cvs.sourceforge.net/viewvc/kanren/kanren/mini/leanTAP.scm?view=log
25 ;;;
26 ;;; This version taken from:
27 ;;; αKanren: A Fresh Name in Nominal Logic Programming
28 ;;; by William E. Byrd and Daniel P. Friedman
29 ;;; Proceedings of the 2007 Workshop on Scheme and Functional Programming
30 ;;; Université Laval Technical Report DIUL-RT-0701
31
32 ;;; To be clear: the original code is MIT-licensed, and the modifications
33 ;;; made to it by Guile are under Guile's license (currently LGPL v3+).
34
35 ;;; Code:
36
37 (define-module (system base pmatch)
38 #:export (pmatch))
39
40 (define-syntax pmatch
41 (syntax-rules (else guard)
42 ((_ (op arg ...) cs ...)
43 (let ((v (op arg ...)))
44 (pmatch v cs ...)))
45 ((_ v) (if #f #f))
46 ((_ v (else e0 e ...)) (let () e0 e ...))
47 ((_ v (pat (guard g ...) e0 e ...) cs ...)
48 (let ((fk (lambda () (pmatch v cs ...))))
49 (ppat v pat
50 (if (and g ...) (let () e0 e ...) (fk))
51 (fk))))
52 ((_ v (pat e0 e ...) cs ...)
53 (let ((fk (lambda () (pmatch v cs ...))))
54 (ppat v pat (let () e0 e ...) (fk))))))
55
56 (define-syntax ppat
57 (syntax-rules (_ quote unquote)
58 ((_ v _ kt kf) kt)
59 ((_ v () kt kf) (if (null? v) kt kf))
60 ((_ v (quote lit) kt kf)
61 (if (equal? v (quote lit)) kt kf))
62 ((_ v (unquote var) kt kf) (let ((var v)) kt))
63 ((_ v (x . y) kt kf)
64 (if (pair? v)
65 (let ((vx (car v)) (vy (cdr v)))
66 (ppat vx x (ppat vy y kt kf) kf))
67 kf))
68 ((_ v lit kt kf) (if (eq? v (quote lit)) kt kf))))