[英]R5RS scheme code find sum of the even elements in a list(recursive and higher order abstractions)?
(define mylist (list 1 2 3 5 8 9 10))
;;sum of the squares of the even elements of mylist
(define (evens lis)
(cond (;; Check stop condition 1
(null? lis)
'())
(;; Check stop condition 2: list of length = 1
(null? (cdr lis))
'())
(else
;; Check: Building list with second element
;; The previous cond clauses have already sorted out
;; that lis and (cdr lis) are not null.
(cons (cadr lis)
;; Check: Recurse "the rest of the rest" of lis with cddr
(evens (cddr lis))))))
(define (sum-even lis)
(if (null? lis)
0
(+ (expt (car lis) 2) (sum-even(cdr lis))))) ;;add all squared even elements
(sum-squared-even (evens mylist))
這是我嘗試查找列表中偶數元素的平方和。 但是,我對r5rs真的很陌生, 是否可以將這些方案僅編寫到一個過程中? 另外, 還要求我編寫有關map,foldr和filter的第二個版本 。 希望任何熟悉r5rs的人都能幫助我! 謝謝!
首先,您的功能是錯誤的,因為您沒有測試列表編號的均勻性。 這應該是正確的定義:
;;even elements of a list
(define (evens lis)
(cond (;; Check stop condition
(null? lis)
'())
(;; Check if first element is even,
;; return it with the evens of the rest of the list
(even? (car lis))
(cons (car lis) (evens (cdr lis))))
(else
;; First element is odd, return only the evens of the rest of the list
(evens (cdr lis)))))
然后,為了回答您的第一個問題,這是一個具有單個遞歸函數的解決方案:
;;sum of the squares of the even elements of a list
(define (sum-square-evens lis)
(cond ((null? lis)
0)
(;; Recurring, first case: the first element is even, so square it
;; and add to the result of summing the square of the evens of the rest of the list
(even? (car lis))
(+ (expt (car lis) 2)
(sum-square-evens (cdr lis))))
(else
;; Recurring, when the first element is not even
;; the result is obtained by summing the square of the evens of the rest of the list
(sum-square-evens (cdr lis)))))
最后是用foldl-map-filter
編寫的函數:
(define (sum-square-evens-2 lis)
(foldl + 0 (map (lambda(x) (expt x 2)) (filter even? lis))))
但是請注意, foldl
不是R5RS Scheme的原始功能,因此您應使用具有#lang racket
規范的DrRacket運行程序,或者定義它或加載定義了它的庫。
這是第二個函數的含義:
filter
將謂詞應用於列表的所有元素,a返回一個新列表,其中包含滿足謂詞的所有元素。 在這種情況下,謂詞是even?
,這樣的結果(filter even? lis)
是所有的偶數的列表lis
。 map
高階函數,以產生結果將應用到其第二個參數(列表)的第一個參數(在這種情況下,將其參數平方的函數)的結果。 因此(map ...)
的結果是一個新列表,其中包含原始列表的所有偶數元素的平方。 (foldl + 0 (n1 n2 ...nk))
返回(...((0 + n1) + n2) + ... + nk)
,因為它反復將二進制函數+
應用於列表,使用0
作為其第一個(左)操作數。 (請注意,在這種情況下, foldl
和foldr
是等效的,第二個計算的和為(n1 + (n2 + ...(nk + 0)...))
) 這就是我要做的; 我將為您提供sum
和square
的定義:
(sum (map square (filter even? '(1 2 3 5 8 9 10))))
在啟動Scheme解釋器時會自動加載的庫中收集諸如sum
和square
類的便利函數非常方便,因此您可以毫不延遲地編寫這樣的簡單表達式。
您的sum_even
名稱可能錯誤,因為它將每個元素平方並加在一起,因此square-sum
也許是一個更好的名稱。
如果您希望對偶數放置的元素進行平方和求和,則只需使用已發布的兩個過程:
(define (square-sum-even lst)
(square-sum (evens lst)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.