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!
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
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!).