带有方案的列表中有多少个元素
我需要编写一个函数,用方案语言计算列表中有多少元素。
例如
(howMany 'a)
返回 0(howMany '(ab))
返回 1(howMany '(a (bc)))
返回 2
我该怎么做?我不需要一个工作代码,只是一个想法。所以也许你应该考虑删除工作代码。 :) 谢谢
i need to write a function which calculates how many elements on list with scheme language.
for example
(howMany 'a)
returns 0(howMany '(a b))
returns 1(howMany '(a (b c)))
returns 2
how can i do that? i did not want a working code, just only an idea for do that. so maybe you should consider to remove working codes. :) thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
折叠答案会起作用。但是,如果这是家庭作业,您可能会尝试仅使用简单的内置函数来完成此操作。有两个可能的答案。
这是简单的方法:(
您的Scheme 实现可能有一个函数
empty?
而不是null?
。)但是,该算法将占用与列表中的元素数量,因为在执行任何添加之前,它将存储列表中每个元素的
(+ 1 ...)
。直觉上,你不应该需要这个。这里有一个更好的算法可以避免这个问题:(加分:使用Scheme的
(let iter ...)
语法来更简洁地编写这个。我使用这种风格是因为如果你只知道一些,它会更清晰方案原语。)The fold answers will work. However, if this is homework, you may be trying to do this using only simple built-in functions. There are two possible answers.
Here's the naive way:
(Your implementation of Scheme may have a function
empty?
instead ofnull?
.)However, this algorithm will take an amount of space linearly proportional to the number of elements in the list, because it will store
(+ 1 ...)
for each element of the list before doing any of the additions. Intuitively, you shouldn't need this. Here's a better algorithm that avoids that issue:(Bonus points: use Scheme's
(let iter ...)
syntax to write this more succinctly. I used this style because it's more clear if you only know a few Scheme primitives.)这句话很可能会被否决,但是,我不知道方案。然而,我熟悉函数式编程。
如果没有内置功能,请先“折叠”起始值为 0 的列表,然后在每次折叠时添加 1。
This will most likely get down-voted for this phrase, but, I don't know scheme. I am, however, familiar with functional programming.
If there is no built-in for this, start by 'folding' the list with start value of 0 and add 1 on every additional fold.
它只是计算列表中元素的数量。
It is simply counting the number of elements in the list.