Quantcast
Channel: How to add in a list in racket - Stack Overflow
Viewing all articles
Browse latest Browse all 7

Answer by Adam Štafa for How to add in a list in racket

$
0
0

A little late, but here's my take:

(define (sum lloi)  (cond    [(empty? lloi) 0]    [(number? lloi) lloi]    [else (apply + (map sum lloi))]))

The input list may contain numbers, empty lists or lists in the same format as the input list. In order to find the sum of this list, we add up all of its element.

  • if the element is empty list, add 0
  • if the element is a number, add the number
  • if the element is a list, first find the sum of this list, then add it (recursion here)

(map sum lloi) applies the function sum to each element of lloi.

(map sum '(a b c d)) => '((sum a) (sum b) (sum c) (sum d))

(apply + list) adds up all elements of the list. You can't just do it like (+ list), because + takes only numbers as arguments, not lists.

(apply + (1 2 3 4)) => (+ 1 2 3 4)

Viewing all articles
Browse latest Browse all 7

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>