【问题标题】:Returning a list created by applying function parameter to all elements equal to the value/predicate parameter返回通过将函数参数应用于等于值/谓词参数的所有元素创建的列表
【发布时间】:2015-02-12 12:36:48
【问题描述】:

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

;;
;;  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
)

【问题讨论】:

    标签: lambda lisp common-lisp


    【解决方案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))
    

    【讨论】:

    • 非常感谢!语法非常有意义。将 x 等同于另一个前身的伟大想法。这是什么话题?我正在查看 funcall lamba mapcar 函数参数,但只能直接使用它,而不是通过函数传递它。再次感谢!
    • 看起来像“高阶函数”这个话题。
    • 谓词,而不是前置词。 :-)
    猜你喜欢
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-14
    • 2016-09-13
    • 1970-01-01
    • 2011-10-04
    相关资源
    最近更新 更多