「定義了一個程序'reduce-per-key',它是一個過程reducef和一個關聯列表,每個關鍵字與一個列表配對。輸出是一個相同結構的列表,除了每個關鍵字現在與應用reducef其關聯列表」如何在方案中編寫按鍵減少功能?
我已經寫的結果‘地圖每個鍵’和‘組逐鍵’:
(define (map-per-key mapf lls)
(cond
[(null? lls) '()]
[else (append (mapf (car lls))(map-per-key mapf (cdr lls)))]))
(define (addval kv lls)
(cond
[(null? lls) (list (list (car kv)(cdr kv)))]
[(eq? (caar lls) (car kv))
(cons (list (car kv) (cons (cadr kv) (cadar lls)))(cdr lls))]
[else (cons (car lls)(addval kv (cdr lls)))]))
(define (group-by-key lls)
(cond
[(null? lls) '()]
[else (addval (car lls) (group-by-key (cdr lls)))]))
怎麼會有我寫下一步,'按鍵減少'?我也無法確定它是否需要兩個參數或三個參數。
到目前爲止,我想出了:
(define (reduce-per-key reducef lls)
(let loop ((val (car lls))
(lls (cdr lls)))
(if (null? lls) val
(loop (reducef val (car lls)) (cdr lls)))))
然而,與一個測試用例,如:
(reduce-per-key
(lambda (kv) (list (car kv) (length (cadr kv))))
(group-by-key
(map-per-key (lambda (kv) (list kv kv kv)) xs)))
我收到了不正確的參數個數,但是當我嘗試寫它有三個參數,我也收到這個錯誤。任何人都知道我在做什麼錯了?
我相當肯定我已經正確填寫的空白,除了對於(;對密鑰值映射'reducef'的結果)是 –
是(reducef(cdr lls))? @ÓscarLópez –
不用,只需使用內置的'map'程序(在您的Scheme解釋器的文檔中閱讀它)。不要重新發明輪子! –