Pattern Matching

Q&A's, tips, howto's

Pattern Matching

Postby jopython » Sat Mar 14, 2015 5:04 pm

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.
jopython
 
Posts: 123
Joined: Tue Sep 14, 2010 3:08 pm

Re: Pattern Matching

Postby ralph.ronnquist » Sun Mar 15, 2015 3:00 am

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?
ralph.ronnquist
 
Posts: 202
Joined: Mon Jun 02, 2014 1:40 am
Location: Melbourne, Australia

Re: Pattern Matching

Postby jopython » Sun Mar 15, 2015 6:19 am

Ralph,

Yes, i was looking for a macro which will support this kind of a syntax.
jopython
 
Posts: 123
Joined: Tue Sep 14, 2010 3:08 pm

Re: Pattern Matching

Postby ralph.ronnquist » Sun Mar 15, 2015 8:39 am

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.
ralph.ronnquist
 
Posts: 202
Joined: Mon Jun 02, 2014 1:40 am
Location: Melbourne, Australia

Re: Pattern Matching

Postby jopython » Sun Mar 15, 2015 1:07 pm

Ralph,
Thank you for that amazing macro.
jopython
 
Posts: 123
Joined: Tue Sep 14, 2010 3:08 pm


Return to newLISP in the real world

Who is online

Users browsing this forum: No registered users and 2 guests