返回Sum的Lisp函数 [英] Lisp Function that Returns a Sum

查看:200
本文介绍了返回Sum的Lisp函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个奇怪的函数,所以请在这里忍受。此函数应将列表 L 作为参数,并具有 sum 变量。如果 L 不是列表,则应返回 nil 。否则,它应遍历列表中的每个元素并执行以下操作:

I am trying to write a weird function, so bear with me here. This function should take a list L as a parameter and have a sum variable. If L is not a list, it should return nil. Otherwise, it should iterate through each element of the list and do the following:


  • 如果元素是一个数字且小于零,则它应该从总和中减去1。

  • 如果元素是一个数字且大于零,它应该在总和上加1。

  • 如果元素是0或不是数字,那么它应该为总和加0。

这是我的代码,但它返回0无论传入的参数如何:

Here's the code I have, but it returns 0 regardless of arguments passed in:

(defun sigsum (L)
  (let ((sum 0))                   ;;variable sum
  (if (not (listp L))              ;;if L is not a list
      nil                          ;;return nil
      (dotimes (i (length L))      ;;otherwise loop through L
        (if (numberp (elt L i))    ;;if each element is a number
            (if (< (elt L i) 0)    ;;if is less than 0 subtract 1 from sum
                (- sum 1)
            (if (> (elt L i) 0)    ;;if greater than 0 add 1 to sum
                (+ sum 1))
            (+ sum 0))             ;;else add 0 to sum
          (+ sum 0)))              ;;not a number so add 0 to sum
  )
  sum)                             ;;return sum
)

与往常一样,非常感谢任何帮助。

As always, any help is greatly appreciated.

推荐答案

(defun discrete (lis)
 (cond
  ((and (listp lis) (not (equal lis nil)))
   (let ((sum 0))
    (loop for item in lis do
     (cond ((or (not (numberp item)) (equal 0 item)) t)
      ((and (numberp item) (> item 1)) (setf sum (+ 1 sum)))
      ((and (numberp item) (< item 1)) (setf sum (- sum 1)))))
    sum))))

用法:(离散'(-1 2 3 0 2 2 -1 2 34 0 -1)) => 3

(离散'( - 4 ab)) => -1

(离散'()) =>无

(离散'(asdf)) => 0

这篇关于返回Sum的Lisp函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆