N
N
nconc2019-03-13 09:12:50
Lisp
nconc, 2019-03-13 09:12:50

How to define a function that generates a set of functions from n to m similar to Lisp 1+?

Task: Define a function that generates a set of functions from n to m similar to Lisp 1+.
For example: function 8+ takes 1000 and returns 1008.
Common Lisp variants:

(defun make-function-number-plus (n m)
  (loop for a from n to m do
        (make-function (add-plus a) '(z) `(+ z ,a))))
 
(defun add-plus (a)
  (read-from-string
   (concatenate 'string (write-to-string a) "+")))
 
(defun make-function (name prms body)
  (eval `(defun ,name ,prms ,body)))

> (make-function-number-plus 2 10)
NIL
> (7+ 1000)
1007
; автор – helter, www.cyberforum.ru
(defun make-function-number-plus (n m)
  (loop for a from n to m do
        (let ((a a))
          (setf (symbol-function (add-plus a))
                (lambda (z) (+ z a))))))
 
(defun add-plus (a)
  (intern (format nil "~A+" a)))
 
> (make-function-number-plus 2 10)
NIL
> (7+ 1000)
1007

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Onyma, 2020-11-19
@Onyma

Creating an arbitrary function from a string:

(eval (read-from-string "(defun test-make-fun () (format t \"test-make-fun is ok!\"))"))

The same, but from the list:
(eval '(defun test-make-fun2 () (format t "test-make-fun2")))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question