| Paste number 50967: | match |
| Pasted by: | Cin |
| When: | 1 year, 7 months ago |
| Share: | Tweet this! | http://paste.lisp.org/+13BR |
| Channel: | #scheme |
| Paste contents: |
;; Expresses
;; (1) constants; numbers, strings
;; (2) symbols
;; (3) variables
;; Examples
;; (match '(n) '(42)) => (42)
;; (match '(n 5) '(42 5)) => (42 5)
;; (match '(n 0) '(42 5)) => error
(define (match pattern match-list)
(let check ((tokens pattern) (items match-list) (result '()))
(if (pair? tokens)
(if (pair? items)
(let ((item (car items))
(token (car tokens)))
(cond ((symbol? token)
(check (cdr items) (cdr tokens) (append! result (list item))))
((number? token)
(if (and (number? item) (= item token))
(check (cdr items) (cdr tokens) (append! result (list item)))
(error (format "Unable to match item ~a to token ~a" item token))))
((string? token)
(if (and (string? item) (string=? item token))
(check (cdr items) (cdr tokens) (append! result (list item)))
(error (format "Unable to match item ~a to token ~a" item token))))
(else (error "Invalid pattern " pattern))))
(error (format "Unable to match pattern ~a for list ~a" pattern match-list)))
result)))Annotations for this paste:
| Annotation number 2: | with map |
| Pasted by: | Cin |
| When: | 1 year, 7 months ago |
| Share: | Tweet this! | http://paste.lisp.org/+13BR#2 |
| Paste contents: |
(define (match pattern match-list)
(define (check token item)
(define (validate correct? equal?)
(if (and (correct? item) (equal? item token))
item
(error (format "Unable to match item ~a to token ~a" item token))))
(cond ((symbol? token) item)
((number? token) (validate number? =))
((string? token) (validate string? string=?))
(else (error "Invalid pattern " pattern))))
(map check pattern match-list))| Annotation number 1: | match slightly improved |
| Pasted by: | Cin |
| When: | 1 year, 7 months ago |
| Share: | Tweet this! | http://paste.lisp.org/+13BR#1 |
| Paste contents: |
(define (match pattern match-list)
(let check ((tokens pattern) (items match-list) (result '()))
(if (pair? tokens)
(if (pair? items)
(let* ((item (car items))
(token (car tokens))
(append (lambda ()
(check (cdr items) (cdr tokens) (append! result (list item)))))
(validate (lambda (correct? equal?)
(if (and (correct? item) (equal? item token))
(append)
(error (format "Unable to match item ~a to token ~a" item token))))))
(cond ((symbol? token) (append))
((number? token) (validate number? =))
((string? token) (validate string? string=?))
(else (error "Invalid pattern " pattern))))
(error (format "Unable to match pattern ~a for list ~a" pattern match-list)))
result)))