计算列表中项目之间的增量
Calculate deltas between items in a list
如果我有一个值列表,计算列表中元素之间差异的有效方法是什么?
例如:
'(5 10 12 15)
将导致 '(5 2 3)
,或 '(0 5 2 3)
谢谢!
为此你只需要 partition
,然后是常规 mapv
(或 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])))
请务必查看 the Clojure CheatSheet 以快速参考此类函数(每天阅读!)。
你也会这样做:
(def xs '(5 10 12 15))
(map - (rest xs) xs)
;; => (5 2 3)
map
将函数 -
应用于两个列表:
10 12 15
- 5 10 12 15
----------------
5 2 3
如果我有一个值列表,计算列表中元素之间差异的有效方法是什么?
例如:
'(5 10 12 15)
将导致 '(5 2 3)
,或 '(0 5 2 3)
谢谢!
为此你只需要 partition
,然后是常规 mapv
(或 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])))
请务必查看 the Clojure CheatSheet 以快速参考此类函数(每天阅读!)。
你也会这样做:
(def xs '(5 10 12 15))
(map - (rest xs) xs)
;; => (5 2 3)
map
将函数 -
应用于两个列表:
10 12 15
- 5 10 12 15
----------------
5 2 3