Page 1 of 1
Exploding a list using patterns
Posted: Sat Nov 03, 2012 9:39 pm
by jopython
Is there a Lisp pattern where I can explode a list which has BEGIN and END markers
Code: Select all
("exb" "BEGIN" "unknown" "num" "of" "items" "END" "BEGIN" "ex3" "END" "something" "and" "so" "on" )
To
Code: Select all
(("BEGIN" "unknown" "num" "of" "items" "END") ("BEGIN" "ex3" "END"))
The builtin explode function doesnt allow custom functions where we can
accomplish this.
Re: Exploding a list using patterns
Posted: Sun Nov 04, 2012 3:08 am
by winger
Code: Select all
(setf lst '("exb" "BEGIN" "unknown" "num" "of" "items" "END" "BEGIN" "ex3" "END" "something" "and" "so" "on" ))
(setf ix (map (fn (x) (first x)) (ref-all {BEGIN|END} lst regex)))
(push 0 ix)
(apply (fn (, y z) (println (push ( y (inc (- z y)) lst) result -1))) ix 3)
;result
(("BEGIN" "unknown" "num" "of" "items" "END") ("BEGIN" "ex3" "END"))
or
Code: Select all
(dolist (e lst)
(cond ((= e "END") (and tmplst (push tmplst result -1) (setf bid nil tmplst nil)))
((true? bid) (push e tmplst -1))
((= e "BEGIN") (and (setf bid true) (push e tmplst -1))))
)
;result
(("BEGIN" "unknown" "num" "of" "items") ("BEGIN" "ex3"))
May be we need a match-all function :)
Re: Exploding a list using patterns
Posted: Sun Nov 04, 2012 3:52 am
by winger
winger wrote:Code: Select all
(setf lst '("exb" "BEGIN" "unknown" "num" "of" "items" "END" "BEGIN" "ex3" "END" "something" "and" "so" "on" ))
(setf ix (map (fn (x) (first x)) (ref-all {BEGIN|END} lst regex)))
(push 0 ix)
(apply (fn (, y z) (println (push ( y (inc (- z y)) lst) result -1))) ix 3)
;result
(("BEGIN" "unknown" "num" "of" "items" "END") ("BEGIN" "ex3" "END"))
or
Code: Select all
(dolist (e lst)
(cond ((= e "END") (and tmplst (push tmplst result -1) (setf bid nil tmplst nil)))
((true? bid) (push e tmplst -1))
((= e "BEGIN") (and (setf bid true) (push e tmplst -1))))
)
;result
(("BEGIN" "unknown" "num" "of" "items") ("BEGIN" "ex3"))
May be we need a match-all function :)
Re: Exploding a list using patterns
Posted: Sun Nov 04, 2012 5:01 am
by jopython
Thank you winger for your timely responses.
It is interesting to see how newLisp allows you to use symbols (tmplst and result) without 'declaring' ahead.
I am not used to that kind of thinking. Is that considered good practice?
Re: Exploding a list using patterns
Posted: Mon Nov 05, 2012 8:11 am
by Lutz
using match for the same task:
Code: Select all
(setf lst
'("exb" "BEGIN" "unknown" "num" "of" "items" "END" "BEGIN" "ex3" "END" "something" "and" "so" " on" ))
(while (set 'm (match '(* "BEGIN" * "END" *) lst))
(println "===>" (m 1))
(set 'lst (last m)))
;===>("unknown" "num" "of" "items")
;===>("ex3")
Re: Exploding a list using patterns
Posted: Mon Nov 05, 2012 12:38 pm
by jopython
Thanks Lutz for that terse, and at the same time intuitive code.
I wish match also accepts regular expressions. Something like this.
Code: Select all
(match '(* {BEGIN} * "END" *) lst)