Scheme 中检查列表长度是否为偶数的函数
您好,我已经编辑了方案中检查列表长度是否偶数的函数代码。
(define even-length?
(lambda (l)
(cond
((null? l)#f)
((equal? (remainder (length(l)) 2) 0) #t)
(else #f))))
正确吗?
Hi I have edited the code for function in scheme that checks whether the length of a list is even.
(define even-length?
(lambda (l)
(cond
((null? l)#f)
((equal? (remainder (length(l)) 2) 0) #t)
(else #f))))
Is it corrrect?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您似乎将
if
和cond
的语法都混淆了。我建议参考语言参考。if
只有两个子句,并且您不必为 else 子句编写else
。 (提示:此函数根本不需要if
。)此外,请考虑如果列表为
null< 则返回
null
是否有意义。 /代码>;也许您想返回#t
或#f
。哦,是的,并将您的
length
调用重写为正确的前缀样式方案函数调用。You seem to have the syntax for
if
andcond
all mixed up. I suggest referring to the language reference.if
only has two clauses, and you don't writeelse
for the else clause. (Hint: You shouldn't need anif
for this function at all.)Also, consider whether it makes sense to return
null
if the list isnull
; probably you want to return#t
or#f
instead.Oh yeah, and rewrite your call of
length
to be a proper prefix-style Scheme function call.该代码显然是错误的 - 您的
%2
假设为中缀表示法,其中 Scheme 使用前缀表示法。您的if
的语法也是错误的 - 对于if
,else
是隐式的(即您有if 条件 true在这种情况下,您试图从一条腿返回 #t,并从另一条腿返回 #f——您可以只返回您在
中测试的表达式。 >if
。编辑:另一个细节——你真的应该将其重命名为
even-length?
,即使我假设它是一个谓词,例如even。
对我来说意味着(even 3)
应该返回#f
,而(even 4)
应该返回# t
- 但在这种情况下,两者都不起作用Edit2:因为 mquander 已经给了你一个版本的代码,我想我会这样写:
我不。就像使用小写“l”(但它本身)一样,所以我将其大写。因为
even?
是内置的,所以我使用它而不是查找余数。
这与您的情况在某一方面有所不同:空列表的长度为 0,被认为是偶数,因此:(
偶数长度? `())
给出#t。
The code is clearly wrong -- your
%2
assuming infix notation, where Scheme uses prefix notation. The syntax of yourif
is wrong as well -- for anif
, theelse
is implicit (i.e. you haveif condition true-expression false-expression
. In this case, you're trying to return #t from one leg and #f from another leg -- that's quite unnecessary. You can just return the expression that you tested in theif
.Edit: one other detail -- you should really rename this to something like
even-length?
. Even if I assume that it's a predicate, a name likeeven
would imply to me that(even 3)
should return#f
, and(even 4)
should return#t
-- but in this case, neither works at all.Edit2: Since mquander already gave you one version of the code, I guess one more won't hurt. I'd write it like:
I don't like using lower-case 'l' (but itself) much, so I've capitalized it. Since
even?
is built in, I've used that instead of finding the remainder.Running this produces:
This is different from what you had in one respect: the length of an empty list is 0, which is considered an even number, so:
(even-length? `())
gives #t.
用法:
正如其他人指出的那样,确实有一个谓词来检查数字的均匀性,那么为什么不使用它呢?
编辑:我刚刚看到 Jerry Coffin 使用相同的示例编写了相同的函数...抱歉重复:-)
Usage:
As others pointed out, there is indeed a predicate to check evenness of a number, so why not using it?
EDIT: I just saw Jerry Coffin wrote the same function witht the same example... Sorry for repeating :-)