Lisp中的默认编程 [英] Tacit programming in Lisp

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

问题描述

是否可以在Lisp中使用/实现默认编程(也称为无点编程)?如果答案是肯定的,那么已经完成了吗?

Is it possible to use/implement tacit programming (also known as point-free programming) in Lisp? And in case the answer is yes, has it been done?

推荐答案

原则上,这种样式的编程在CL中是可能的,但是作为Lisp-2,必须添加多个#'funcall .此外,例如,与Haskell相比,CL中不对函数进行管理,并且没有隐式的部分应用程序.总的来说,我认为这样的风格不是非常习惯的CL.

This style of programming is possible in CL in principle, but, being a Lisp-2, one has to add several #'s and funcalls. Also, in contrast to Haskell for example, functions are not curried in CL, and there is no implicit partial application. In general, I think that such a style would not be very idiomatic CL.

例如,您可以这样定义部分应用程序和组成:

For example, you could define partial application and composition like this:

(defun partial (function &rest args)
  (lambda (&rest args2) (apply function (append args args2))))

(defun comp (&rest functions)
  (flet ((step (f g) (lambda (x) (funcall f (funcall g x)))))
    (reduce #'step functions :initial-value #'identity)))

(这些只是我快速举过的例子-并未针对不同用例进行过真正的测试或深思熟虑.)

(Those are just quick examples I whipped up – they are not really tested or well thought-through for different use-cases.)

有了这些,Haskell中的map ((*2) . (+1)) xs变为:

With those, something like map ((*2) . (+1)) xs in Haskell becomes:

CL-USER> (mapcar (comp (partial #'* 2) #'1+) '(1 2 3))
(4 6 8)

sum示例:

CL-USER> (defparameter *sum* (partial #'reduce #'+))
*SUM*
CL-USER> (funcall *sum* '(1 2 3))
6

(在此示例中,您也可以设置符号的函数单元格,而不是将函数存储在值单元格中,以避开funcall.)

(In this example, you could also set the function cell of a symbol instead of storing the function in the value cell, in order to get around the funcall.)

顺便说一下,在Emacs Lisp中,部分应用程序内置为apply-partially.

In Emacs Lisp, by the way, partial application is built-in as apply-partially.

在Qi/Shen中,函数是咖喱的,并且支持隐式部分应用程序(当使用一个参数调用函数时):

In Qi/Shen, functions are curried, and implicit partial application (when functions are called with one argument) is supported:

(41-) (define comp F G -> (/. X (F (G X))))
comp

(42-) ((comp (* 2) (+ 1)) 1)
4

(43-) (map (comp (* 2) (+ 1)) [1 2 3])
[4 6 8]

在Clojure中也有句法线程化糖,它具有类似的流水线"感觉:

There is also syntactic threading sugar in Clojure that gives a similar feeling of "pipelining":

user=> (-> 0 inc (* 2))
2

这篇关于Lisp中的默认编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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