【问题标题】:Typesafe and argument safe division in common lispcommon lisp 中的类型安全和参数安全划分
【发布时间】:2012-01-20 05:28:10
【问题描述】:

长话短说,我需要 defun ts_div 并允许它成为常规 / 的类型安全和“参数安全”版本

基本上,我希望它接受一个包含任意数量的数字(甚至没有)的列表,并且能够像这样调用它:

(ts_div (123 321 23))

或:

(ts_div somelist)

想要的结果:如果列表中有两个以上的项目,第一个将除以第二个,其余的被忽略。如果第二个数字是 0,它应该返回第一个数字的值。如果列表为空,则应返回 0。

关于如何实现这一目标的任何建议?

旁注:我做了一些测试,试图让它的加法变体。基本上,总结在列表上下文中传递给它的任何数字,但正如预期的那样,它抱怨列表中的第一项不是函数,我一直无法弄清楚这是如何缓解的。

【问题讨论】:

    标签: lisp common-lisp type-safety


    【解决方案1】:

    嗯。类似于

    (defun ts-div (list)
       (check-type list list)
       (destructuring-bind (&optional (first 0 got-first) (second 0 got-second) &rest ignored) list
           (declare (ignore ignored))
           (if got-second 
               (if (zerop second) first (/ first second)) 
               (if got-first first 0))))
    

    我认为可能可行。

    CL-USER> (ts-div '())
    0
    CL-USER> (ts-div '(1))
    1
    CL-USER> (ts-div '(1 0))
    1
    CL-USER> (ts-div '(1 2))
    1/2
    CL-USER> (ts-div '(1 2 123))
    1/2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 2018-10-25
      • 2023-04-05
      • 1970-01-01
      相关资源
      最近更新 更多