Search code examples
listvectorsumschemechez-scheme

How do I get the sum of all elements >10 in a given list using chez scheme?


If create a chez scheme ex which makes SUM of all elements from lista_de_elemente

(define lista_de_elemente (list 2 4 1 12 32 3 34 12))

(define suma
    (lambda()
        (apply + lista_de_elemente)))

How do I make the sum of only elements greater than 10?


Solution

  • The general technique is to first form the list of elements you want to process. You already have this list. Then, you want to apply one or more transformations to the input list. In this case, we don't need to make any transformations. Then, you filter the list to only get elements that satisfy a certain condition. Finally, you apply operations that combine elements in the filtered list.

    This general way of processing lists is described in SICP as

    enumerate -> transform (map) -> filter -> accumulate
    

    Now, in this case, we don't need to enumerate or map anything because we already have our input list as I mentioned earlier.

    (define (filter predicate sequence) (cond
       ((null? sequence) '())
       (else (cond
       ((predicate (car sequence)) (cons (car sequence) (filter predicate (cdr sequence))))
       (else (filter predicate (cdr sequence)))))))
    
    
    
    (define (accumulate op initial sequence) (cond
                       ((null? sequence) initial)
                       (else (op (car sequence) (accumulate op initial (cdr sequence))))))
    
    
    (define (sum-list list) (accumulate + 0 (filter (lambda(x) (cond ((> x 10) #t) (else #f)))list)))
    
    
    (sum-list (list 1 2 3 45 12))
    ;Output: 57
    

    The predicate is just a condition that evaluates to true or false.