当施瓦茨想出后来我们称之为施瓦茨变换的东西时,他剽窃了Lisp的装饰类--取消装饰的成语。我所有的Lisp知识在九个半辈子都消失了,但我在SBCL上试了一试。我的目标是一个惯用的例子,我可以用在介绍施瓦茨变换的历史。
这是可行的(我知道我可以进一步推广它),但我想知道Lisp-y是如何实现的:
(require :sb-posix)
(defun schwartzian-files-mtime ( glob-pattern )
(map
'list
#'cdr
(stable-sort
(map
'list (
lambda (x) (
cons
(sb-posix:stat-mtime (sb-posix:stat x))
x
)
)
(directory glob-pattern)
)
#'<
:key
#'car
)
)
)
(schwartzian-files-mtime "/etc/*")发布于 2016-08-11 13:01:01
函数中没有足够的LISP是用于括号的样式(它们不应该单独作为一行的最后一个元素保留,它们应该放在所括形式的最后一行上)。另一个次要的问题是,您可以使用较短的mapcar而不是map 'list。
下面是您的函数的一个版本(对于应用于数据和任何谓词的任何函数),它遵循在Common中使用的更传统的样式。
(defun schwartzian-transform (list costly-function predicate)
"sort a list of objects over the value of a function applied to them,
by applying the Schwartzian Transform (https://en.wikipedia.org/wiki/Schwartzian_transform)
the parameters are the list, the function, and the predicate for the sort."
(mapcar #'cdr
(stable-sort (mapcar (lambda (x)
(cons (funcall costly-function x) x))
list)
predicate
:key #'car)))
(require :sb-posix)
(schwartzian-transform
(directory "/etc/*")
(lambda (x) (sb-posix:stat-mtime (sb-posix:stat x)))
#'<=)发布于 2016-08-11 18:30:48
当然,非常非语言性的是你的开头父母结束了这样的代码行。有了它,mapcar和显式#'在lambda前面,它看起来就像
(defun schwartzian-files-mtime ( glob-pattern )
(mapcar #'cdr
(stable-sort
(mapcar #'(lambda (x)
(cons (sb-posix:stat-mtime (sb-posix:stat x))
x))
(directory glob-pattern))
#'<
:key #'car)))这在我看来是很自然的,但可能仍然不存在。官方风格指南。它有一种“快速-n-脏”的感觉,就像你会当场涂鸦的东西(不像Randal的原始代码),也不是带有文档字符串的适当的生产代码等等。
https://codereview.stackexchange.com/questions/138428
复制相似问题