2014-09-25 53 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

相關問題