Pattern Matching

Q&A's, tips, howto's
Locked
jopython
Posts: 123
Joined: Tue Sep 14, 2010 3:08 pm

Pattern Matching

Post 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.

ralph.ronnquist
Posts: 228
Joined: Mon Jun 02, 2014 1:40 am
Location: Melbourne, Australia

Re: Pattern Matching

Post 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?

jopython
Posts: 123
Joined: Tue Sep 14, 2010 3:08 pm

Re: Pattern Matching

Post by jopython »

Ralph,

Yes, i was looking for a macro which will support this kind of a syntax.

ralph.ronnquist
Posts: 228
Joined: Mon Jun 02, 2014 1:40 am
Location: Melbourne, Australia

Re: Pattern Matching

Post 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.

jopython
Posts: 123
Joined: Tue Sep 14, 2010 3:08 pm

Re: Pattern Matching

Post by jopython »

Ralph,
Thank you for that amazing macro.

Locked