【问题标题】:How can i count all natural elements in list (using mzscheme)我如何计算列表中的所有自然元素(使用 mzscheme)
【发布时间】:2014-09-25 13:46:17
【问题描述】:

函数名 = mycount

这里是输出示例:

(mycount 20) -> error(must standard error)
(mycount `()) -> 0
(mycount `(1 2 3)) - > 6
(mycount `((1 2) ((3)) (4 (5)))) -> 15

【问题讨论】:

  • (apply + (flatten lst))
  • 好吧,我只是要删除我的答案。
  • 我总是忘记 FP 的强大 BIF 并且我的回答太冗长了,我想 :)
  • @ChristopheDeTroyer 我很确定不允许 OP 使用flatten。而且,顺便说一句,它不适用于第一个用例。
  • countsum 不同。因此,您是否想在(1 2 3) 中计算自然数,它是3 而不是6

标签: list count scheme


【解决方案1】:
function count-numbers takes a list:
    define a counter
    is it a number?
       ERROR
    is it a list?
        for each element of list:
            cond
                - is it a number? -> increase the counter
                - is it a list?   -> apply (count-numbers) to it and add the result to counter
                - do nothing

类似的东西?我们不会让你做作业:)

【讨论】:

  • 非惯用方案(即没有功能)
  • 您能详细说明一下吗?还是计数器的定义? (即函数中的赋值)
  • 你变异了counter。一个经典的 roll-your-own Scheme 解决方案是 (let loop ((lst lst)(count 0)) (if (null? lst) count (loop (cdr lst) (if (natural? (car lst)) (+ 1 count) count)))),它通过递归更新计数器。
猜你喜欢
  • 2018-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-21
  • 2020-05-12
相关资源
最近更新 更多