我試圖計算串列串列的第一個數字稱為一、二或三的次數重復了多少次,我制作的代碼的想法是例如選擇稱為“一”的串列串列,然后取里面有“a”的第一個字母,然后在這種情況下將第一個值為“10”的值與此串列中的其他值進行比較,在這種情況下,我應該讓它說“10”重復了一次,然后它將繼續使用其他兩個“b”和“c”,但是在執行以下代碼時
(define a (list 10 2 3 54 6 9 7 10))
(define b (list 5 1 8 6 5 5 4 77 8 6))
(define c (list 80 80 80))
(define e (list 99 156 54 48 99))
(define d (list 16 94 75 30 56 16 8 16))
(define one (list a b c))
(define two (list c e b a))
(define three (list b c d e))
; receives 'one', 'two' or 'three' and finds how many times the first number of the list is repeated in the list of lists
(define (find-repeated-number list)
(define (find-repeated-number-helper list)
(if (null? list)
0
(if (equal? (car list) (car (cdr list)))
( 1 (find-repeated-number-helper (cdr list)))
; displays the number of times the first number of the list is repeated in the list of lists
(find-repeated-number-helper (cdr list)))))
(find-repeated-number-helper list))
(find-repeated-number one)
我收到以下錯誤,為什么?我怎樣才能得到我想做的事?我將不勝感激任何幫助
*** ERROR: pair required, but got ()
While loading "./jdoodle.sc" at line 19
Stack Trace:
_______________________________________
0 (car (cdr list))
at "./jdoodle.sc":14
1 (equal? (car list) (car (cdr list)))
at "./jdoodle.sc":14
Command exited with non-zero status 70
uj5u.com熱心網友回復:
我仍然不確定這個練習的重點是撰寫低級遞回代碼還是使用標準庫提供的一些函式(在這種情況下,count或者是filterand的組合length),但這是我的瘋狂猜測:
(define a (list 10 2 3 54 6 9 7 10))
(define b (list 5 1 8 6 5 5 4 77 8 6))
(define c (list 80 80 80))
(define e (list 99 156 54 48 99))
(define d (list 16 94 75 30 56 16 8 16))
(define one (list a b c))
(define two (list c e b a))
(define three (list b c d e))
(define (find-count lst element)
(count (lambda (n) (= n element))
lst))
(define (print-count lst)
(let ((number-count (find-count (cdr lst) (car lst))))
(write (string-append
"number of times the first number is repeated: "
(number->string (car lst))
" is "
(number->string number-count)
(if (= number-count 1)
" time"
" times")))
(newline)))
(for-each print-count one)
輸出:
"number of times the first number is repeated: 10 is 1 time"
"number of times the first number is repeated: 5 is 2 times"
"number of times the first number is repeated: 80 is 2 times"
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/493067.html
