(组成)在Common Lisp中 [英] (compose) in Common Lisp

查看:60
本文介绍了(组成)在Common Lisp中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在P.Graham的"ANSI Common Lisp"(第110页)中找到了实现该功能的函数生成器.参数是n> 0引号的函数名称.我不完全了解它,因此我将在此处引用代码并在其下面指定我的问题:

We find this function builder to realize composition in P.Graham's "ANSI Common Lisp" (page 110). The arguments are n>0 quoted function names. I don't understand it completely, so I'll quote the code here and specify my questions underneath it:

(defun compose (&rest fns)
  (destructuring-bind (fn1 . rest) (reverse fns)
    #'(lambda (&rest args)
        (reduce #'(lambda (v f) (funcall f v)) 
                rest
                :initial-value (apply fn1 args)))))

要组合的参数列表被反向并解压缩,其(现在是第一个)元素绑定到"fn1",其余元素绑定到"rest".最外面的lambda的主体是reduce:(funcall fi(funcall fi-1 ...)),其操作数取反顺序以恢复初始值.

The argument list to compose is reversed and unpacked, its (now first) element bound to 'fn1' and the rest to 'rest'. The body of the outermost lambda is a reduce: (funcall fi (funcall fi-1 ... ) ), with operands in inverted order to restore the initial one.

1)最外面的lambda表达式的作用是什么?即,它从哪里获得"args"?是否将数据结构指定为destructuring-bind的第一个参数?2)最里面的lambda取自哪里两个参数?

1) What is the role of the outermost lambda expression? Namely, where does it get its 'args' from? Is it the data structure specified as the first argument of destructuring-bind? 2) Where does the innermost lambda take its two arguments from?

我的意思是我可以欣赏代码的功能,但是词汇范围对我来说还是个谜.期待任何评论!提前致谢,//马可

I mean I can appreciate what the code does but still the lexical scope is a bit of a mystery to me. Looking forward to any and all comments! Thanks in advance, //Marco

推荐答案

如果先考虑几个实际示例,可能会更容易:

It's probably easier if you consider first a couple of practical examples:

(defun compose1 (a)
  (lambda (&rest args)
    (apply a args)))

(defun compose2 (a b)
  (lambda (&rest args)
    (funcall a (apply b args))))

(defun compose3 (a b c)
  (lambda (&rest args)
    (funcall a (funcall b (apply c args)))))

所以最外面的 lambda 是返回值:一个接受任何参数的函数,它的作用是应用last函数,并以相反的顺序将所有其他函数链接到从last获得的结果上功能.

So the outermost lambda is the return value: a function that takes any arguments, what it does with it is applying the last function and chaining all the others in reverse order on the result got from last function.

注意: compose1 可以更简单地定义为(defun compose1(a)a).

Note: compose1 could be defined more simply as (defun compose1 (a) a).

可能是一个等效但效率较低的版本

A somewhat equivalent but less efficient version could be

(defun compose (&rest functions)
  (if (= (length functions) 1)
      (car functions)
      (lambda (&rest args)
        (funcall (first functions)
                 (apply (apply #'compose (rest functions))
                        args)))))

这篇关于(组成)在Common Lisp中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆