如果我有一个值列表,那么计算列表中元素之间差异的有效方法是什么?
例如:
'(5 10 12 15)
将产生'(5 2 3)
或'(0 5 2 3)
谢谢!
答案 0 :(得分:4)
您也可以这样做:
(def xs '(5 10 12 15))
(map - (rest xs) xs)
;; => (5 2 3)
map
将函数-
应用于两个列表:
10 12 15
- 5 10 12 15
----------------
5 2 3
答案 1 :(得分:1)
您只需要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,以快速参考此类功能(每天阅读!)。