Lisp function chain macro

Is there a ready-made lisp macro that allows you to bind (bind) functions? I could not find him. I will try to explain what I mean with this example.

Instead of using let * with many unused intermediate variables, such as:

(let*
  ((var1 (f1 x y))
   (var2 (f2 x var1))
   (var3 (f1 var2 z)))
 var3)

I would like it to be written like this:

(->
  (f1 x y)
  (f2 x _)
  (f1 _ z))

where, obviously, _ will be the return value from the previous expression. Plus, if one could use _1 , _2 , ... to refer to previously returned values.

This is an idea; the exact syntax is not so important.

I know that it is not so difficult to write, but it seems so useful that it should already be written.

+3
5

- ?

(defun chain-expander (forms)
  (cond ((null (cdr forms)) (car forms))
    (t `(let ((it ,(car forms)))
          ,(chain-expander (cdr forms))))))

(defun chain-counted-expander (forms counter)
  (cond ((null (cdr forms)) (car forms))
    (t (let* ((name (format nil "_~d" counter))
          (anaphora (or (find-symbol name) (intern name))))
         `(let ((,anaphora ,(car forms)))
        ,(chain-counted-expander (cdr forms) (1+ counter)))))))

(defmacro chain (&body forms)
  (chain-expander forms))

-, _1, _2 .. , CHAIN-EXPANDER CHAIN-COUNTED-EXPANDER ( , 0 1). , _N , , _ , .

+6

(f1 (f2 x (f1 x y)) z)

?

?

+4

Lisp

(defmacro alambda (parms &body body)
  `(labels ((self ,parms ,@body))
     #'self))

(defmacro ablock (tag &rest args)
  `(block ,tag
     ,(funcall (alambda (args)
            (case (length args)
              (0 nil)    
          (1 (car args))
          (t `(let ((it ,(car args)))    ;; change it to _ 
            ,(self (cdr args))))))
       args)))

"it", "_", . , → , .

+2
+1

: Lisp

My answer to this question is similar to Batting's answer to this question, but without counting; as a side note, I think that counting is dangerously fragile - you can introduce reordering errors when updating the code. It is probably best to give a way to name the previous results, but in practice I rarely need results other than the last. If you need them, perhaps you should write a function instead of a chain expression.

0
source

Source: https://habr.com/ru/post/1730537/


All Articles