Recursion & Polymorphism

Fixme work in progress

The following sum function will calculate the value of adding all the elements in a collection. You can alter the results by adding a starting value to the calculation as a second argument when calling sum

  1. (defn sum
  2. ([vals] (sum vals 0))
  3. ([vals accumulating-total]
  4. (if (empty? vals)
  5. accumulating-total
  6. (sum (rest vals) (+ (first vals) accumulating-total)))))
  7. (sum [2 7 9 11 13])
  8. (sum [1])
  9. (sum [2 7 9 11 13] 9)

Rather than duplicate the calculation, the behaviour of calling sum with just a collection simply calls sum again, this time passing a starting value of zero.