Skip to content

Convenient accessor patterns

Masataro Asai edited this page Apr 20, 2017 · 3 revisions

LAST pattern

last pattern is a wrapper around CL:LAST. Matches against a list, and matches subpatterns against N last elements obtained by CL:LAST.

Syntax
last subpattern &optional (n 1)
(match '(:a :b :c)
  ((last (list b _) 2)
    b))
;; -> :b

READ pattern

Syntax
read subpattern

Useful for simple parsing (especially in combination with trivia.ppcre:split pattern)

The current matching object should be a string. subpattern is matched against the result of reading the string by read-from-string. end-of-file and parse-error are ignored and the matching will be successful, where subpattern is matched against NIL.

(defun main (argv)
  (match argv
    ((list (read a) (read b) (read c))
     (+ a b c))))

(main '("1" "2" "3")) ;; -> 6

(use-package :trivia.ppcre)
(match "1 2 3"
  ((split (read a) (read b) (read c))
   (+ a b c)))
;; -> 6