cameyo wrote: ↑Tue Mar 30, 2021 2:07 pm
Function to create a function with name and parameters:
Code: Select all
(define (make-add name val)
(let (f nil)
(setq f (string "(define (" name " x) (+ " val " x))"))
(setq name (eval-string f))
name))
Creating a function
Code: Select all
(make-add "sum-10" 10)
out: (lambda (x) (+ 10 x))
Using the created function
Do you know of another way (instead of using strings) to create a function with another function?
your example of a made-add function to create a sum-10 function:
Code: Select all
(define (make-add n v)
(evaluate (list 'define (list n 'x) (list '+ v 'x))))
and using it:
Code: Select all
(make-add 'sum-10 10)
out: (lambda (x) (+ 10 x))
(sum-10 3)
out: 13
a more general way to create any funcion with name n having parameters a and a body b with minor checking of parameters and function name:
Code: Select all
(define (mkf n a b)
(evaluate (and (symbol? n) (list 'define (if (apply and (map symbol? (cons n a))) (cons n a) n) b))))
and using it:
Code: Select all
(mkf 'sum-x-y '(x y) '(+ x y))
out: (lambda (x y) (+ x y))
sum-x-y
out: (lambda (x y) (+ x y))
(sum-x-y 4 5)
out: 9
the function expects name and parameters to be symbols and defaults to a symbol definition if you pass bad parameters, that is paremeters which are not symbols, in this case is defines a symbol with the name passed and the evaluated body as value (or nil if evaluation fails). If the name of the function to be defined is not a symbols it returns nil and doesn't define anything:
Code: Select all
x
out: nil
y
out: nil
(mkf 'sum-x-y-with-bad-parameters '(x y 3) '(+ x y))
out: ERR
sum-x-y-with-bad-parameters
out: nil
(define x 3)
out: 3
(define y 34)
out: 34
(mkf 'sum-x-y-with-bad-parameters '(x y 3) '(+ x y))
out: 37
sum-x-y-with-bad-parameters
out: 37
(mkf 4 '(x y 3) '(+ x y))
out: nil
(mkf nil '(x y) '(+ x y))
out: nil
Take this as an example about how to face the question, of course it needs more checking to be robust and correct (variable capture...).
Note: in this post "evaluate" means "eval", because phpBB does not allow me to type it even in code section, so assume this code as the very begining: