PLEAC examples - 6. Pattern Matching
6.0. Introduction
Note: PicoLisp has no strings, and doesn't operate on symbol names directly. Instead, patterns are applied to lists.6.0.1 Example
# The match returns T if it succeeded to match the pattern : (match '(@Name had a @Adj lamb) '(Mary had a little lamb)) -> T : @Name -> (Mary) : @Adj -> (little)
6.1. Copying and Substituting Simultaneously
You're tired of constantly using two separate statements with redundant information, one to copy and another to substitute.6.1.1. Example
# Example 1 - Replace 'town' bt 'village'
: (replace '(here in this town) 'this 'that 'town 'village)
-> (here in that village)
# Example 2 - With / as delimiter, return the last part
: (setq F (chop "abc/def/ghi"))
-> ("a" "b" "c" "/" "d" "e" "f" "/" "g" "h" "i")
: F
-> ("a" "b" "c" "/" "d" "e" "f" "/" "g" "h" "i")
: (split F '/)
-> (("a" "b" "c") ("d" "e" "f") ("g" "h" "i"))
: (last (split F '/))
-> ("g" "h" "i")
: (stem F '/)
-> ("g" "h" "i")
: (pack '("g" "h" "i"))
-> "ghi"
# Example 2 - Same, but now in one go ...
: (let F (chop "abc/def/ghi")
(prinl (pack (last (split F '/))))
(prinl (pack (stem F '/))) )
ghi
ghi
-> "ghi"
# Example 3 - Make All Words Title-Cased
: (mapcar
'((W) (pack (uppc (car W)) (cdr W)))
(split (chop "Mary had a little lamb") " ") )
-> ("Mary" "Had" "A" "Little" "Lamb")
# Example 4 - Replace 'man3' by 'cat3'
: (glue '/
(replace
(split (chop "/usr/man/man3/foo.1") "/")
'("m" "a" "n" "3")
'("c" "a" "t" "3") ) )
-> "/usr/man/cat3/foo.1"
# Example 5 - Replace last part of substrings delimited by / with 'lib'
: (mapcar
'((S) (pack (glue '/ (head -1 (split (chop S) '/))) "/lib"))
'("/usr/bin" "/bin" "/usr/local/bin") )
-> ("/usr/lib" "/lib" "/usr/local/lib")
6.2. Matching Letters
You want to see whether a value only consists of alphabetic characters.6.2.1. Example
# Is my input list purely alphabetic?
: (de isalpha? (Lst)
(fully
'((C)
(or (>= "Z" C "A") (>= "z" C "a")) )
Lst ) )
-> NIL
: (isalpha? '(a b c d e f g h))
-> T
: (isalpha? '(a b c D e f G h))
-> T
: (isalpha? (1 2 3))
-> NIL
6.3. Matching Words
You want to pick out words from a string.6.3.1. Example
# Returns the first space delimited word of the input
: (make
(find
'((C) (or (sp? C) (nil (link C))))
(chop "abcd efg") ) )
-> ("a" "b" "c" "d")
# Returns first part of the input up to any char that is not [ A..Z | a..z| ' | - ]
: (make
(find
'((C)
(nand
(or (>= "Z" C "A") (>= "z" C "a") (sub? C "`-"))
(link C) ) )
(chop "ab`c-d/e") ) )
-> ("a" "b" "`" "c" "-" "d")
http://picolisp.com/wiki/?pcepleacmatching
| 23jun18 | ArievW |
