[英]Does Lisp have something like Haskell's takeWhile function?
我是 Common Lisp 的新手。 在 Haskell 中,您可以执行以下操作:
Prelude> takeWhile (<= 10) [k | k <- [1..]]
[1,2,3,4,5,6,7,8,9,10]
这在 Lisp 中可行吗? 不一定是无限列表,而是任何列表。
你可以使用LOOP :
(setq *l1* (loop for x from 1 to 100 collect x))
(loop for x in *l1* while (<= x 10) collect x)
如果你真的需要它作为单独的 function:
(defun take-while (pred list)
(loop for x in list
while (funcall pred x)
collect x))
我们在这里:
T1> (take-while (lambda (x) (<= x 10)) *l1*)
(1 2 3 4 5 6 7 8 9 10)
但是如果我们比较:
(loop for x in *l1* while (<= x 10) collect x)
(take-while (lambda (x) (<= x 10)) *l1*)
我想我会坚持使用循环。
对于无限序列,您可以查看Series :
T1> (setq *print-length* 20)
20
T1> (setq *l1* (scan-range :from 1))
#Z(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ...)
T1> (until-if (lambda (x) (> x 10)) *l1*)
#Z(1 2 3 4 5 6 7 8 9 10)
这应该做...
(defun take-while (list test)
(and list (funcall test (car list))
(cons (car list) (take-while (cdr list) test))))
(take-while '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) (lambda (x) (< x 10)))
--> (1 2 3 4 5 6 7 8 9)
然而,这种“自然”实现不是尾递归的,并且可能会因大列表而崩溃。
一个明确的 push-nreverse 方法(一种常见的模式)可以是
(defun take-while (list test)
(do ((res nil))
((or (null list) (not (funcall test (car list))))
(nreverse res))
(push (car list) res)
(setf list (cdr list))))
递归(但尾递归,因此可能适用于大多数 CL 实现)可以 IMO 如下:
(defun take-while (list test)
(labels ((rec (res x)
(if (and x (funcall test (car x)))
(rec (cons (car x) res) (cdr x))
(nreverse res))))
(rec nil list)))
请注意,但不能保证通用 lisp 实现将处理尾调用优化。
某些语言提供 Haskell 样式列表 API 作为 3rd 方库,支持或不支持无限流。
一些例子:
请记住,在序列上实现takeWhile
相对容易,在 Haskell 中给出如下:
takeWhile _ [] = []
takeWhile p (x:xs)
| p x = x : takeWhile p xs
| otherwise = []
您可以使用闭包(来自Paul Graham 的 On Lisp )在 common lisp 中进行惰性评估:
(defun lazy-right-fold (comb &optional base)
"Lazy right fold on lists."
(labels ((rec (lst)
(if (null lst)
base
(funcall comb
(car lst)
#'(lambda () (rec (cdr lst)))))))
#'rec))
然后,take-while 变成:
(defun take-while (pred lst)
(lazy-right-fold #'(lambda (x f) (
(if (test x)
(cons x (funcall f))
(funcall f)))
nil))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.