0

If I have a list of values, what is an effective way to calculate the difference between the elements in the list?

For example: '(5 10 12 15) would result in '(5 2 3), or '(0 5 2 3)

Thanks!

mac
  • 858
  • 1
  • 6
  • 11

2 Answers2

4

You would do this also:

(def xs '(5 10 12 15))

(map - (rest xs) xs)
;; => (5 2 3)

map applies the function - to two lists:

  10  12  15
-  5  10  12  15
----------------
   5   2   3
rmcv
  • 1,956
  • 1
  • 9
  • 8
1

You just need partition for this, then a regular mapv (or map):

(ns tst.demo.core
  (:use tupelo.core tupelo.test)
  (:require
    [tupelo.string :as ts] ))

(dotest
  (let [data   [5 10 12 15]
        pairs  (partition 2 1 data)
        deltas (mapv (fn [[x y]] ; destructure pair into x & y
                       (- y x))  ; calculate delta
                 pairs)]
    (is= pairs [[5 10] [10 12] [12 15]])
    (is= deltas [5 2 3])))

Be sure to see the Clojure CheatSheet for fast reference to functions like this (read it every day!).

Alan Thompson
  • 29,276
  • 6
  • 41
  • 48