2014-09-25 50 views
-2

函数名= mycount的我怎么能算在列表中的所有自然元素(使用的MzScheme)

这里是输出例如:

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

'(apply +(flatten lst))' – uselpa 2014-09-25 14:17:12

+0

嗯,我只是要删除我的答案。 – 2014-09-25 14:17:51

+0

我总是忘记FP的强大BIF,我的答案太冗长了,我认为:) – 2014-09-25 14:19:45

回答

-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 

类似的东西?我们不打算做你的功课:)

+0

非惯用方案(即不起作用) – Sylwester 2014-09-25 14:37:43

+0

请您详细说明一下吗?或者是柜台的定义? (即在函数中赋值) – 2014-09-25 14:38:21

+1

你可以改变'counter'。一个经典的roll-your-own Scheme解决方案应该是(let loop((lst lst)(count 0))(if(null?lst)count(loop(cdr lst)(if(natural?(car lst))( + 1计数)计数))))'递归更新计数器。 – Sylwester 2014-09-25 14:43:24

相关问题