Page 1 of 1
Pattern Matching
Posted: Sat Mar 14, 2015 5:04 pm
by jopython
Once you get into ML languages, you get used to pattern matching:
Here is an factorial example in Shen.
Code: Select all
(26-) (define factorial
0 -> 1
X -> (* X (factorial (- X 1))))
factorial
(27-) (factorial 6)
720
I wonder if anybody done anything like this for beloved newLisp?
Thanks and Cheers.
Re: Pattern Matching
Posted: Sun Mar 15, 2015 3:00 am
by ralph.ronnquist
I'm not sure the example justifies the issue, but doesn't
letex give you this?
I mean, a corresponding newlisp articulation could look like:
Code: Select all
(define (factorial n)
(case n
(0 1)
(true (eval (letex (X n) '(* X (factorial (- X 1))))))))
(although a plain
(* n (factorial (- n 1))) would be easier to read)
Or, maybe you are looking for a more exact "rule form" syntax?
Re: Pattern Matching
Posted: Sun Mar 15, 2015 6:19 am
by jopython
Ralph,
Yes, i was looking for a macro which will support this kind of a syntax.
Re: Pattern Matching
Posted: Sun Mar 15, 2015 8:39 am
by ralph.ronnquist
I gave it a shot, since I haven't tried macros before. Of course, I didn't want to redefine
define so I opted for using the similar word
xxxx, and eventually I arrived at the following
define-macro:
Code: Select all
(define-macro (xxxx name)
(letn ((argv (explode (args) 3)) (tail (pop argv -1)))
(eval (letex ((ARG (tail 0)) (NAME name)
(BODY (extend (list 'case (tail 0))
(map (fn (a) (select a 0 2)) argv)
(list (list true (tail 2))))))
'(define (NAME ARG) BODY)))))
This just employs the
case solution, and it completely ignores the expected "->" elements. I guess there's actually more syntax to deal with, but this would eat the example you gave, and repeat the suggested effect.
I couldn't figure out a
macro to do this, as it seems to need more processing than a single expand clause.
Re: Pattern Matching
Posted: Sun Mar 15, 2015 1:07 pm
by jopython
Ralph,
Thank you for that amazing macro.