Pattern Matching

Started by jopython, March 14, 2015, 10:04:56 AM

Previous topic - Next topic

jopython

Once you get into ML languages, you get used to pattern matching:

Here is an factorial example in Shen.



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

rrq

#1
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:
(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

#2
Ralph,



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

rrq

#3
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:
(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

#4
Ralph,

Thank you for that amazing macro.