【问题标题】:Counting words which aren't starting with given letter计算不是以给定字母开头的单词
【发布时间】:2020-10-31 13:54:22
【问题描述】:

所以我在 Lisp 中编写了这个函数,它计算列表中有多少单词不是以给定字母开头。 但是我现在需要编辑它并且不在我的函数中使用“let”(但保留“char”和“string”)。 当我开始 Lisp 不久,感觉有点受阻!任何人都可以帮助我吗?

示例: (others 'n '(art nose foot nose take silence never)) => 4

这就是我所做的,但需要删除“让”:

(defun others (x liste)
  (let ((c (char (string x) 0)))
    (cond
      ((not liste) 0)
      ((char= (char (string (car liste)) 0) c) (others x (cdr liste)))
      (t (+ 1 (others x (cdr liste)))) ) ) )

【问题讨论】:

  • 测试空列表的函数称为null

标签: lisp common-lisp clisp


【解决方案1】:

另一种内置方式是这样的:

> (count 'n
         '(art nose foot nose take silence never)
         :test #'(lambda (a b)
                   (string/= a b :end1 1 :end2 1)))
-> 4

【讨论】:

    【解决方案2】:

    这是一个迭代版本:

    (loop for word in '("art" "nose" "foot" "nose" "take" "silence" "never")
          for c = #\n
          count (not (char= c (char word 0))))
    

    (循环可以通过https://lispcookbook.github.io/cl-cookbook/iteration.html的例子来学习)

    【讨论】:

      【解决方案3】:

      一种解决方案是在参数列表中使用&aux 变量。这使您可以像let 那样在函数中绑定变量。这几乎是一种在函数开头使用let 而不显式使用let 的方法。

      (defun others (x liste &aux (c (char (string x) 0)))
         (cond
            ((not liste) 0)
            ((char= (char (string (car liste)) 0) c) (others x (cdr liste)))
            (t (+ 1 (others x (cdr liste))))))
      

      【讨论】:

      • 非常感谢!我考虑过 &aux 但不确定如何将它与 char 一起使用!
      • @valerie 由于 c 只使用一次,另一种解决方案是根本不绑定变量,只需在使用 c 的地方替换 (char (string x) 0)
      猜你喜欢
      • 1970-01-01
      • 2018-09-03
      • 2023-02-21
      • 2014-01-02
      • 2022-01-08
      • 1970-01-01
      • 2021-03-12
      • 1970-01-01
      • 2020-07-28
      相关资源
      最近更新 更多