Clojure function for first differences, second differences,...,nth differences - clojure

Inputting a vector I'd like to write a function that gives successive differences between elements. Ideally the function should input a vector x and parameter n that designates nth difference.
Sample in the form [x n]
Input 1: [16 10 8 6 4 2] 1 (1 for first difference)
Output 1: [-6 -2 -2 -2 -2]
Input 2: [16 10 8 6 4 2] 2
Output 2: [4 0 0 0 nil nil]
Symbolically here's what is going on for sample 2 (meant as illustration of idea, not Clojure code)
[a b c d e f] 2
[a-2b+c, b-2c+d, c-2d+e, d-2e+f]

Here you go:
(def a [16 10 8 6 4 2])
(defn diff [a]
(map - (rest a) a))
(defn diff-n [a n]
(nth (iterate diff a) n))
(diff-n a 1) ; => (-6 -2 -2 -2 -2)
(diff-n a 2) ; => (4 0 0 0)

Same as #Shlomi 's answer but with an optional step size parameter:
(defn diff
([a]
(map - (next a) a))
([a step]
(map - (nthnext a step) a)))
(defn nthdiff
([a n]
(nth (iterate diff a) n))
([a n step]
(nth (iterate #(diff % step) a) n)))

Related

Tribonacci function in Clojure [duplicate]

This question already has an answer here:
Creating the tribonacci numbers in Clojure
(1 answer)
Closed 7 years ago.
Is there a different,cleaner way of generating tribonacci?
(defn tribonacci [x](last (reduce
(fn [[a b c] n]
(conj [b c] (+ a b c))) [0 0 1] (range (- x 3)))))
Here's how I would write it:
(defn tribonacci [a b c]
(lazy-seq (cons a (tribonacci b c (+' a b c)))))
If you want to get the nth tribonacci number, just use, for instance, (tribonacci 0 0 1) and then call nth on that.
you can create a lazy sequence of these numbers, and take the needed element from it:
user> (def t (lazy-cat [1 1 2] (map +' t (rest t) (nthrest t 2))))
#'user/t
user> (take 20 t)
(1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 5768 10609 19513 35890 66012)
replace [1 1 2] to [0 1 1], if you need them starting from 0

How to move first list item to the end?

For given list:
(1 2 3 4)
I'd like to get as output:
(2 3 4 1)
Code I came up with looks like this:
(flatten (cons (rest l) (list (first l))))
However my feeling is, that I overcomplicated this. Any other ideas?
You don't need to flatten a cons, just use concat.
Here is an example:
(let [fruit ["apple" "orange" "grapes" "bananas"]]
(concat (rest fruit) [(first fruit)])
Developing #stonemetal's hint, we can quickly and lazily rotate a vector thus:
(defn rotate [v n]
(let [cv (count v), n (mod n cv)]
(concat (subvec v n cv) (subvec v 0 n))))
It works in either direction:
(map #(rotate (vec (range 5)) %) (range -2 8))
;((3 4 0 1 2)
; (4 0 1 2 3)
; (0 1 2 3 4)
; (1 2 3 4 0)
; (2 3 4 0 1)
; (3 4 0 1 2)
; ...
; (2 3 4 0 1))
So to rotate the first in a sequence to the end:
(rotate (vec (range 1 5)) 1)
You can also use destructuring (either on the function arguments or in a let binding).
(let [[h & tail] '(1 2 3 4)]
(concat tail (list h))) ;=> (1 2 3 4)

Clojure - how to do reductions function but drop state?

If I use the reductions function like so:
(reductions + [1 2 3 4 5])
Then I get
(1 3 6 10 15)
Which is great - but I'd like to apply a binary function in the same way without the state being carried forward - something like
(magic-hof + [1 2 3 4 5])
leads to
(1 3 5 7 9)
ie it returns the operation applied to the first pair, then steps 1 to the next pair.
Can someone tell me the higher-order function I'm looking for? (Something like reductions)
This is my (non-working) go at it:
(defn thisfunc [a b] [(+ a b) b])
(reduce thisfunc [1 2 3 4 5])
You can do it with map:
(map f coll (rest coll))
And if you want a function:
(defn map-pairwise [f coll]
(map f coll (rest coll)))
And if you really need the first element to remain untouched (thanx to juan.facorro's comment):
(defn magic-hof [f [x & xs :as s]]
(cons x (map f s xs)))
partition will group your seq:
user> (->> [1 2 3 4 5] (partition 2 1) (map #(apply + %)) (cons 1))
(1 3 5 7 9)
So, you want to apply a function to subsequent pairs of elements?
(defn pairwise-apply
[f sq]
(when (seq sq)
(->> (map f sq (next sq))
(cons (first sq)))))
Let's try it:
(pairwise-apply + (range 1 6))
;; => (1 3 5 7 9)
This is sufficient:
(#(map + (cons 0 %) %) [1 2 3 4 5])
;; => (1 3 5 7 9)

Building tables in clojure

If I wanted to build a table in Clojure of vector duplicates, I'd write:
(take 2 (repeat [1 2 3]))
But how would I expand this notion of a table function to build something like:
Input 1: [a^2 2 6 2] where a^2 is some input function, 2 is min value, 6 is max value, and 2 is step size.
Output 1: [4,16,36]
Input 2: [b^2 10 -5 -2]
Output 2: [100 64 36 16 4 0 4 16]
This outputs a 4x3 matrix
Input 3: [(+ (* 10 i) j) [1 4] [1 3]]
where (+ (* 10 i) j) is 10i+j (some given input function), [1 4] is the min and max of i, and [1 3] is the min and max of j.
Output 3: [[11 12 13] [21 22 23] [31 32 33] [41 42 43]]
You want to use for in a nested fashion:
(for [i (range 1 (inc 4))]
(for [j (range 1 (inc 3))]
(+ (* 10 i) j)))
;; '((11 12 13) (21 22 23) (31 32 33) (41 42 43))
EDIT: expanded with an example implementation
For example:
(defn build-seq [f lower upper step]
(for [i (range lower (+ upper step) step)]
(f i)))
(build-seq #(* % %) 2 6 2)
;; '(4 16 36)
(defn build-table [f [ilower iupper] [jlower jupper]]
(for [i (range ilower (inc iupper))]
(for [j (range jlower (inc jupper))]
(f i j))))
(build-table #(+ (* 10 %) %2) [1 4] [1 3])
;; '((11 12 13) (21 22 23) (31 32 33) (41 42 43))
Your three input/output samples do not display a consistent signature for one variable and two ; furthermore, the step argument seems to be optional. I'm skeptical about the existence of a nice API that would retain the samples' syntax, but I can try something different (even if I do believe the simple embedded for forms are a better solution):
(defn flexible-range [{:keys [lower upper step] :or {lower 0}}]
(let [[upper step] (cond
(and upper step) [(+ upper step) step]
step (if (pos? step)
[Double/POSITIVE_INFINITY step]
[Double/NEGATIVE-INFINITY step])
upper (if (< lower upper)
[(inc upper) 1]
[(dec upper) -1])
:else [Double/POSITIVE_INFINITY 1])]
(range lower upper step)))
(defn build-table
([f [& params]]
(for [i (flexible-range params)]
(f i)))
([f [& iparams] [& jparams]]
(for [i (flexible-range iparams)]
(for [j (flexible-range jparams)]
(f i j)))))
(build-table #(* % %) [:lower 2 :upper 6 :step 2])
;; '(4 16 36)
(build-table #(+ (* 10 %) %2) [:lower 1 :upper 4]
[:lower 1 :upper 3])
;; '((11 12 13) (21 22 23) (31 32 33) (41 42 43))
I think you can easily solve it with map and range
(defn applier
[f ini max step]
(map f (range ini (+ max step) step)))
(applier #(* % %) 2 6 2)
=> (4 16 36)
This fn can resolve your third example
(defn your-fn [[ra1 ra2] [rb1 rb2] the-fn]
(vec (map (fn [i] (vec (map (fn [j] (the-fn i j)) (range rb1 (inc rb2))))) (range ra1 (inc ra2))))
)
(your-fn [1 4] [1 3] (fn [i j] (+ (* 10 i) j)))
=> [[11 12 13] [21 22 23] [31 32 33] [41 42 43]]
But i'd need a few more specification details (or more use cases) to make this behavior generic, maybe you can explain a little more your problem. I think the 1st-2nd and the 3rd examples don't take the same type of parameters and meaning, (step vs seq ). So the #Guillermo-Winkler solves part the problem and my-fn will cover the last example

In clojure, how to build lazy sequence using iterate function

The clojure document gives the following examples:
(take 10 (iterate (partial + 2) 0))
(def powers-of-two (iterate (partial * 2) 1))
(take 10 powers-of-two)
(def fib (map first (iterate (fn [[a b]] [b (+ a b)]) [1 1])))
(take 10 fib)
Anyone can explain the syntax of clojure's iterate function in more detail? I am very confused with all the usage. Why two brackets are there in (fn [[a b]] [b (+ a b)])?
Another example can be found here:
(defn iter [[x y]]
(vector y (+ x y)))
(nth (iterate iter [0 1]) 10000)
iterate takes a function f and an initial value x and produces a lazy sequence. The first element in the seq is x. Each subsequent element is computed by calling f with the previous element.
Example 1:
(iterate (partial + 2) 0)
This generates a sequence, starting at 0, where each element is the previous element with 2 added to it. I.e.:
0
(+ 2 0) ; => 2
(+ 2 2) ; => 4
(+ 2 4) ; => 6
; etc
Each element in the seq is passed to (partial + 2) when generating the following element.
Example 2:
(iterate (partial * 2) 1)
This generates a sequence, starting at 1, where each element is the previous element multiplied by 2. I.e.:
1
(* 2 1) ; => 2
(* 2 2) ; => 4
(* 2 4) ; => 8
(* 2 8) ; => 16
; etc
Again, you can see how each element feeds into the generation of the next one.
Example 3:
(iterate (fn [[a b]] [b (+ a b)]) [1 1])
Firstly, (fn [[a b]] ...) is a way to destructure a value into parts. In this case, the function accepts a two-element vector and unpacks it into the local variables a and b.
The function returns a two-element vector containing b and the sum of a and b (i.e. the second value in the previous pair and the sum of both values in the previous pair).
With this in mind, this iterate call generates:
[1 1]
[1 (+ 1 1)] ; => [1 2]
[2 (+ 1 2)] ; => [2 3]
[3 (+ 2 3)] ; => [3 5]
[5 (+ 3 5)] ; => [5 8]
; etc
Then (map first ...) grabs the first value in each pair, which gives you your Fibonacci sequence.