常见Lisp中的类型安全和参数安全划分 [英] Typesafe and argument safe division in common lisp

查看:105
本文介绍了常见Lisp中的类型安全和参数安全划分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

长话短说,我需要defun ts_div并允许它成为常规/

Long story short I need to defun ts_div and allow it to be a typesafe and "argument safe" version of the regular /

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

Basically, I want it to accept a list with any number of numbers in it (even none), and be able to call it like this:

(ts_div (123 321 23))

或:

(ts_div somelist)

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

Desired result: if there are more than two items in the list, the first will be divided by the second, and the rest is ignored. If the second number is 0, it should return the value of the first number instead. If the list is empty, it should return 0.

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

Any suggestions on how to achieve this?

侧注::我做了一些测试,试图使它具有加法变量.基本上,对在列表上下文中传递给它的任何数字求和,但是正如预期的那样,它抱怨列表中的第一项不是函数,而且我一直无法弄清楚如何缓解这种情况.

Sidenote: I did some testing trying to make the addition-variant of it. Basically, sum up whatever numbers are passed to it in a list context, but as expected it complains about the first item in the list not being a function, and I've been unable to figure out how this is mitigated.

推荐答案

Hm.类似于

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

我认为

可能会工作.

might work, I think.

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

这篇关于常见Lisp中的类型安全和参数安全划分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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