I am trying to design a function that, given a list of numbers, returns the squares of the even numbers in a supplied list. I do not want to compute squares that will not be used in the end result.
This is what I have using map and filter:
; even-squares-only : [List-of Number] -> [List-of Number]
; returns square of only even numbers in a supplied list
(define (even-squares-only lon)
(map (λ (n) (sqr n)) (filter even? lon)))
How would I go about designing the same function using the foldr function so that I can iterate over the elements of the list once instead of twice (I am trying to use local or lambda in this function as well)?
In ISL with lambda:
(define (even-squares-only lon)
(foldr (lambda (element result)
(if (even? element)
(cons (sqr element) result)
result))
'()
lon))
This exercise can be even done without local
and lambda
, if you rewrite the anonymous function into a named one:
(define (reducing-fn element result)
(if (even? element)
(cons (sqr element) result)
result))
(define (even-squares-only lon)
(foldr reducing-fn
'()
lon))
Example:
> (even-squares-only '(1 2 3 4 5 6 7 8 9 10))
(list 4 16 36 64 100)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.