Clojure / core.matrix / initialize 2d array - clojure

In clojure a 2-d array can be initialized with a value like so:
(defn vec2d
"Return an x by y vector with all entries equal to val."
[x y val]
(vec (repeat y (vec (repeat x val)))))
Is there maybe a core.matrix built-in feature that would do the job?

You can use new-matrix and fill:
(require '[clojure.core.matrix :as matrix])
(defn vec2d
"Return an x by y vector with all entries equal to val."
[x y val]
(matrix/fill (matrix/new-matrix y x) val))
If you need the result to be a regular 2D Clojure vector, you can call to-nested-vectors on the result. At that point, though, you're probably better off just using the original solution from your question.

Related

Clojure macro to allow writing code without let bindings

I am trying to write a macro that will allow me to do the following
(without-nesting
(:= x 1)
(:= y 2)
(:= z 3)
(db-call x y z)
(:= p 33)
(db-call x y z p))
becomes
(let [x 1
y 2
z 3]
(db-call x y z)
(let [p 33]
(db-call x y z p)))
So far my implementation has been the following
(defn assignment?
[[s _]]
(= s ':=))
(defmacro without-nesting
[& body]
(let [[bindings xs] (split-with assignment? body)
[non-bindings remaining] (split-with (complement assignment?) xs)]
`(let [~#(mapcat rest bindings)]
~#non-bindings
~(when (seq remaining)
`(without-nesting ~#remaining)))))
I'm having issues when remaining is going to be empty. In my current implementation a nil gets placed which prevents the last form in non-bindings to return its value. I have no clue on how to proceed with a recursive macro. Can someone help
UPDATE:
So I was able to get rid of the nil but I just want to know if there's a better way to deal with this
(defmacro without-nesting
[& body]
(let [[bindings xs] (split-with assignment? body)
[non-bindings remaining] (split-with (complement assignment?) xs)]
`(let [~#(mapcat rest bindings)]
~#non-bindings
~#(if (seq remaining)
[`(without-nesting ~#remaining)]
[]))))
Also would this be a good way to write code? Or do you see any caveats? For me it looks more linear as compared to nested let
I do see how ppl may abuse this. In the case of let, if the nesting becomes too much, then it's a hint to refactor the code. This might hide that
Just use let. It is already recursive. To incorporate function calls where you only care about the side effects, the convention is to bind to an underscore.
(let [x 1
y 2
z 3
_ (db-call x y z)
p 33
_ (db-call x y z p)])

Appending an element at nth index

I'm working on a function, which takes a vector (possibly nested vector) as input along with some quantity y and index n. Essentially the function would append y after the nth element in the vector and adjoin the remaining elements. So far I have the following written, which isn't not working as planned:
(defn funcs [x y n]
(concat (take (- n 1) x) (concat (take-last (- (count x) n) y))))
If you want to return a vector as the final value, you'll have to concatenate your vectors using into (in time linear in the size of the right operand) or core.rrb-vector's catvec (logarithmic time, but the resulting vector will be somewhat slower overall).
As for the actual implementation, assuming you want to go with core.rrb-vector:
(require '[clojure.core.rrb-vector :as fv])
(defn append-after-nth [x y n]
(fv/catvec (fv/subvec x 0 n) y (fv/subvec x n)))

Partial out all but i-th variable in variadic function in Clojure

I'm starting out learning Clojure, and was trying to implement some basic numerical derivative functions for practice. I'm trying to create a gradient function that accepts an n-variable function and the points at which to evaluate it. To do this in a "functional" style, I want to implement the gradient as a map of a 1-variable derivatives.
The 1-variable derivative function is simple:
(defn derivative
"Numerical derivative of a univariate function."
[f x]
(let [eps 10e-6] ; Fix epsilon, just for starters.
; Centered derivative is [f(x+e) - f(x-e)] / (2e)
(/ (- (f (+ x eps)) (f (- x eps))) (* 2 eps))))
I'd like to design the gradient along these lines:
(defn gradient
"Numerical gradient of a multivariate function."
[f & x]
(let [varity-index (range (count x))
univariate-in-i (fn [i] (_?_))] ; Creates a univariate fn
; of x_i (other x's fixed)
;; For each i = 0, ... n-1:
;; (1) Get univariate function of x_i
;; (2) Take derivative of that function
;; Gradient is sequence of those univariate derivatives.
(map derivative (map univariate-in-i varity-index) x)))
So, gradient has variable arity (can accept any # of x's), and the order of the x's counts. The function univariate-in-i takes an index i = 0, 1, ... n-1 and returns a 1-variable function by partial-ing out all the variables except x_i. E.g., you'd get:
#(f x_0 x_1 ... x_i-1 % x_i+1 ... x_n)
^
(x_i still variable)
map-ping this function over varity-index gets you a sequence of 1-variable functions in each x_i, and then map-ping derivative over these gets you a sequence of derivatives in each x_i which is the gradient we want.
My questions is: I'm not sure what a good way to implement univariate-in-i is. I essentially need to fill in values for x's in f except at some particular spot (i.e., place the % above), but programmatically.
I'm more interested in technique than solution (i.e., I know how to compute gradients, I'm trying to learn functional programming and idiomatic Clojure). Therefore, I'd like to stay true to the strategy of treating the gradient as a map of 1-d derivatives over partialed-out functions. But if there's a better "functional" approach to this, please let me know. I'd rather not resort to macros if possible.
Thanks in advance!
Update:
Using Ankur's answer below, the gradient function I get is:
(defn gradient
"Numerical gradient of a multivariate function."
[f & x]
(let [varity-index (range (count x))
x-vec (vec x)
univariate-in-i
(fn [i] #(->> (assoc x-vec i %) (apply f)))]
(map derivative (map univariate-in-i varity-index) x)))
which does exactly what I'd hoped, and seems very concise and functional.
You can define univariate-in-i as shown below. (Assuming that all the other position values are defined in some var default which is a vector)
(fn [i] #(->>
(assoc default i %)
(apply f)))
if you find this abit difficult to comprehend (in the context of how to implement gradient), another variant of multivariable gradient implementation using clojure:
then, given f and vector v of a1,....,aN, will differentiate while all the variables except xi are fixed:
(defn partial-diff [f v i]
(let [h 10e-6
w (update v i + h)]
(/ (- (apply f w) (apply f v))
h)))
(defn gradient [f v]
(map #(partial-diff f v %) (range (count v))))
=>
(gradient (fn [x y]
(+ (* x x) (* x y y))) [3 3])
=> (15.000009999965867 18.000030000564493)

Can you pass data to next iteration in (for ...)?

I am in the progress of learning clojure after work and I'm doing this by making a small game (loving the quil library) to make me familiar with the different aspects of clojure in specific and FP in general.
So, my game world exists of 3d grid of map data strucutures (vector of a vector of a vector of a map). I want to itterate over every point in 3d space (map) and change the data when a condition is met. This was my initial solution:
(the game data structure is the game state (a map))
(defn soil-gen [game]
(let [world-x (game :world-x)
world-y (game :world-y)
world-z (game :world-z)]
(for [x (range world-x)
y (range world-y)
z (range world-z)
:when (> z (* world-z (rand)))]
(assoc-in game [:world x y z :type] :soil))))
But this returns a list of the results (my game state data structure) of every iteration instead of one game data structure. I should somehow be able to pass the result of each iteration back to for. Something like loop/recur probably but I think you cant combine recur with for.
Somebody a clue?
thanks
What you can do is use reduce with for as shown below:
(defn soil-gen [game]
(let [world-x (game :world-x)
world-y (game :world-y)
world-z (game :world-z)]
(reduce (fn [g [x y z]] (assoc-in g [:world x y z :type] :soil)))
game
(for [x (range world-x)
y (range world-y)
z (range world-z)
:when (> z (* world-z (rand)))]
[x y z]))))
You probably want to use something like reduce to pass the accumulated result between each iteration.
Simplified examples:
(reduce
(fn [m val] (assoc m val (str "foo" val)))
{} ;; initial value for m
(range 5)) ;; seqence of items to reduce over
=> {4 "foo4", 3 "foo3", 2 "foo2", 1 "foo1", 0 "foo0"}
reduce is generally very useful whenever so have some concept of an "accumulated value" in functional programming. It also has the advantage of being very efficient.

Different solutions for Clojure implementation of problem

Here is a problem Statement :
Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.
The solution is long,
(defn large [x y]
(if (> x y) x y))
(defn large-3 [x y z]
(if(> (large x y) z) (large x y) z))
(defn small [x y]
(if (< x y) x y))
(defn small-3 [x y z]
(if (< (small x y) z ) (small x y) z))
(defn second-largest [x y z]
(let [greatest (large-3 x y z)
smallest (small-3 x y z)]
(first (filter #(and (> greatest %) (< smallest %)) [x y z]))))
(defn square [a]
(* a a)
)
(defn sum-of-square [x y z]
(+ (square (large-3 x y z)) (square (second-largest x y z))))
Just wanted to know what different/succinct ways this problem can be solved in Clojure.
(defn foo [& xs]
(let [big-xs (take 2 (sort-by - xs))]
(reduce + (map * big-xs big-xs))))
; why only 3? how about N
(defn sum-of-squares [& nums]
(reduce + (map #(* % %) (drop 1 (sort nums)))))
or if you want "the sum of the greatest two numbers:
(defn sum-of-squares [& nums]
(reduce + (map #(* % %) (take 2 (reverse (sort nums))))))
(take 2 (reverse (sort nums))) fromMichał Marczyk's answer.
(See a sequence version of the problem together with a lazy solution in my second update to this answer below.)
(defn square [n]
(* n n))
;; generalises easily to larger numbers of arguments
(defn sum-of-larger-squares [x y z]
(apply + (map square (take 2 (reverse (sort [x y z]))))))
;; shorter; generalises easily if you want
;; 'the sum of the squares of all numbers but n smallest'
(defn sum-of-larger-squares [x y z]
(apply + (map square (drop 1 (sort [x y z])))))
Update:
To expand on the comments from the above, the first version's straighforward generalisation is to this:
(defn sum-of-larger-squares [n & xs]
(apply + (map square (take n (reverse (sort xs))))))
The second version straightforwardly generalises to the version Arthur posted in the meantime:
(defn sum-of-larger-squares [n & xs]
(apply + (map square (drop n (sort xs)))))
Also, I've seen exactly the same problem being solved in Scheme, possibly even on SO... It included some fun solutions, like one which calculated the some of all three squares, then subtracted the smallest square (that's very straightforward to express with Scheme primitives). That's 'unefficient' in that it calculates the one extra square, but it's certainly very readable. Can't seem to find the link now, unfortunately.
Update 2:
In response to Arthur Ulfeldt's comment on the question, a lazy solution to a (hopefully fun) different version of the problem. Code first, explanation below:
(use 'clojure.contrib.seq-utils) ; recently renamed to clojure.contrib.seq
(defn moving-sum-of-smaller-squares [pred n nums]
(map first
(reductions (fn [[current-sum [x :as current-xs]] y]
(if (pred y x)
(let [z (peek current-xs)]
[(+ current-sum (- (* z z)) (* y y))
(vec (sort-by identity pred (conj (pop current-xs) y)))])
[current-sum
current-xs]))
(let [initial-xs (vec (sort-by identity pred (take n nums)))
initial-sum (reduce + (map #(* % %) initial-xs))]
[initial-sum initial-xs])
(drop n nums))))
The clojure.contrib.seq-utils (or c.c.seq) lib is there for the reductions function. iterate could be used instead, but not without some added complexity (unless one would be willing to calculate the length of the seq of numbers to be processed at the start, which would be at odds with the goal of remaining as lazy as possible).
Explanation with example of use:
user> (moving-sum-of-smaller-squares < 2 [9 3 2 1 0 5 3])
(90 13 5 1 1 1)
;; and to prove laziness...
user> (take 2 (moving-sum-of-smaller-squares < 2 (iterate inc 0)))
(1 1)
;; also, 'smaller' means pred-smaller here -- with
;; a different ordering, a different result is obtained
user> (take 10 (moving-sum-of-smaller-squares > 2 (iterate inc 0)))
(1 5 13 25 41 61 85 113 145 181)
Generally, (moving-sum-of-smaller-squares pred n & nums) generates a lazy seq of sums of squares of the n pred-smallest numbers in increasingly long initial fragments of the original seq of numbers, where 'pred-smallest' means smallest with regard to the ordering induced by the predicate pred. With pred = >, the sum of n greatest squares is calculated.
This function uses the trick I mentioned above when describing the Scheme solution which summed three squares, then subtracted the smallest one, and so is able to adjust the running sum by the correct amount without recalculating it at each step.
On the other hand, it does perform a lot of sorting; I find it's not really worthwhile to try and optimise this part, as the seqs being sorted are always n elements long and there's a maximum of one sorting operation at each step (none if the sum doesn't require adjustment).