返回通过将函数参数应用于等于值/ predicate参数的所有元素而创建的列表

时间:2014-12-14 05:43:03

标签: lambda lisp common-lisp

嘿,我现在已经找了一段时间没有明确的方向。我知道它在funcalls领域但遇到了麻烦。我的两个问题如下。另外,我不确定我是否应该将它们分成两个不同的线程。请帮忙。谢谢!

;;
;;  returns a list created by applying its function parameter to all elements equal to the value parameter. All other elements remain unchanged 
;;

(defun find-and-do (lst val fun)
  "(find-and-do '() 1 (lambda (x) (+ x 1))) → NIL
(find-and-do '(1 2 3) 2 (lambda (x) (* x 2))) → (1 4 3)
(find-and-do '(1 2 3) 2 (lambda (x) (* x 2))) → (1 4 3)
(find-and-do '(1 2 3 4) 2 #'sqrt) → (1 1.4142135623730951 3 4) 
(find-and-do '(a b c) 'b #'list) → (A (B) C) "

;(lambda (x) (funcall fun val ))) ; what I have so far
; I think id instead off val in the call above it would have to simultaneously pull the elements and modify them from a newly copied list
)

;;
;;  same as find-and-do, but instead of matching a value, apply the function parameter to those elements for which the predicate parameter applied results in true. 
;;

(defun test-and-do (lst predp fun)
  "(test-and-do '() #'evenp (lambda (x) (+ x 1))) → NIL
(test-and-do '(1 2 3 4) #'evenp (lambda (x) (* x 2))) → (1 4 3 8)"

; no idea
)

1 个答案:

答案 0 :(得分:1)

以下是我写test-and-do的方法:

(defun test-and-do (lst pred fun)
  (mapcar (lambda (x)
            (if (funcall pred x)
                (funcall fun x)
                x))
          lst))

find-and-do可以test-and-do

实施
(defun find-and-do (lst val fun)
  (test-and-do lst (lambda (x) (equal val x)) fun))