【问题标题】:Sort an element and put it in a variable对元素进行排序并将其放入变量中
【发布时间】:2022-11-20 21:21:45
【问题描述】:

我有捕鸟任务: 编写一个递归函数 SORT-LIST,它从任意数量的“苹果”和“豌豆”列表中挑选出“苹果”并将它们存储在一个可选变量中,最后返回这个可选变量的内容。

我不知道如何修复。那是我的开始。也许有人可以帮助我。非常感谢!!

(defun sort-list (x l)
  (cond ((null l) nil))
  ((equal (first l) x)
   (cons (first l) (sort-list x (rest l))))
  ((sort-list x (rest l))))

【问题讨论】:

    标签: recursion common-lisp


    【解决方案1】:

    这个名字具有误导性。它不是sort,实际上是filter

    (defun applep (x)
      "something looking whether x is an apple or not")
    
    (defun my-filter (pred l &optionals (acc '()))
      (cond ((null l) (nreverse acc))
            ((funcall pred (car l)) (my-filter pred (cdr l) (cons (car l) acc)))
            (t (my-filter pred (cdr l) acc))))
    

    这是内置的 lisps - 所以即使没有定义它,你也可以运行:

    (filter #'applep l)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-27
      • 2017-07-04
      • 2020-09-03
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多