Return function with variable data?

Started by jeremyc, March 10, 2007, 09:30:59 AM

Previous topic - Next topic

jeremyc

Is something like this possible?



(define (create-greeter greeting)
  (lambda (n)
    (println greeting " " n "!")))
(set 'hello-greeter (create-greeter "Hello"))
(set 'goodbye-greeter (create-greeter "Goodbye"))
(hello-greeter "World")
(goodbye-greeter "World")


The obvious desired output is:



Hello World
Goodbye World


Jeremy

m i c h a e l

#1
Hi Jeremy,



Something like this, maybe:


newLISP v.9.1.0 on OSX UTF-8, execute 'newlisp -h' for more info.

> (define (greeter greeting to) (println greeting " " to "!"))
(lambda (greeting to) (println greeting " " to "!"))
> (set 'hello (curry greeter "Hello"))
(lambda (_x) (greeter "Hello" _x))
> (set 'goodbye (curry greeter "Goodbye"))
(lambda (_x) (greeter "Goodbye" _x))
> (hello "World")
Hello World!
"!"
> (goodbye "Cruel World")
Goodbye Cruel World!
"!"
> _


m i c h a e l

Lutz

#2
'curry' is the shortest and preferred way to do it when you have 2 arguments as in Jeremyc's example. The following is a more general solution in case there are more parameters or it is not the 1st one which gets curried.



This uses expand to get the curried variable into the lambda expression:


(define (create-greeter greeting)
    (expand (fn (n) (println greeting " " n "!")) 'greeting))

> (create-greeter "Hello")
(lambda (n) (println "Hello" " " n "!"))

> (define hello-greeter (create-greeter "Hello"))
(lambda (n) (println "Hello" " " n "!"))

> (hello-greater "World")
Hello World!


instead of (define hello-greeter ...) you also could say (set 'hello-greeter ..) as in your code. Both does the same in newLISP, but 'define' is just a little bit more descriptive in this case.



Lutz