2017-09-02 125 views
2

我有疑問,我使用的是球拍,我想列出一個列表的數字,但我不能。我試着用長,但我想,因爲在列表球拍中計數數字

(countDigits「(4 5 6 78))> 5

的答案是5這是行不通的,但我不知道怎麼樣,我有一個數字計數的代碼,但我不知道如何在列表中執行。 ¿我該怎麼做?

+2

'(define count-digits(compose1 string-length string-a podd *(咖喱地圖〜a)))' –

+0

真的很有用,我的想法完全錯了,它的工作,謝謝 –

回答

2

這裏是一個可能的解決方案:

(define (countDigits lst) 
    (apply + 
     (map (compose string-length number->string) 
       lst))) 

說明:

  • 對於列表中,我們把它轉換爲字符串
  • 然後,我們獲得每個字符串的長度每一個數字 - 那會告訴我們的位數
  • 最後我們把所有長度加在一起

例如:

(countDigits '(4 5 6 78)) 
=> 5 
+0

這真的很有幫助,我想到的想法完全不同於此,謝謝 –

0

一個更簡單的例子,不會讓你的教授看兩次:)

定期遞歸:

(define (countDigits list-of-digits) 
    (cond [(empty? list-of-digits) 0] 
     [else (+ 1 (countDigits (rest list-of-digits)))])) 

尾遞歸:

(define (countDigits list-of-digits sum) 
    (cond [(empty? list-of-digits) sum] 
     [else (countDigits (rest list-of-digits) (+ 1 sum))])) 
+0

它拋出我出錯:+:違反合同 預期:數量? 給出:# 參數位置:2nd 其他參數...: –

+0

哈哈......我的不好。如果你看,在我的常規遞歸函數中,我有一個錯位的逗號,我只是直接輸入到SO。語法應該是現在 –