I want to write a function to compute upper triangular nature of matrix. So lets say a_i_j be the number in the i^th row and j^th column. A matrix is
upper-triangular if a_i_j = 0 for all i > j.
Try this:
(defn is-upper-triangular [m]
(->> (map-indexed vector m)
(mapcat (fn [[r v]] (take r v)))
(every? zero?)))
The above code take 0 element from the first row, 1 element from the second row, and 2 elements from the third rows, etc... and checks that all the taken elements are zero. If all are zero, it is upper triangular.
This code does not check that the given matrix is square. You can add this check if it is necessary.
upper-triangular? isn't in the core.matrix API yet, but if you use vectorz-clj you can get at the function with Java interop:
(def a (array :vectorz [[1 2] [0 4]]))
(.isUpperTriangular a)
=> true
(.isUpperTriangular (transpose a))
=> false
Related
I need to write a function in #lang racket that determines the amount of divisors a positive integer has. (Ex: 6 has 4 divisors; 1,2,3,6)
So far I have:
(define (divides a b) (if (= 0 (modulo a b)) #t #f))
I need to use this helper function to write the function (divisors-upto n k) that that computes the number of divisors n has between 1 and k (so it computes the number of divisors of n
up to the value k).
This is easiest done1 with a for loop, in particular for/fold, given that you already have your divides function.
(define (divisors num)
(for/fold ([acc 0]
[n (in-range num)])
(if (divides n num) <acc+1> <acc>)))
Basically, you are looping over the list, and keeping an accumulator, and whenever a number is dividable, increment your accumulator. See if you can fill in the expressions for <acc+1> and <acc> in the code above.
1You could also do this with list length and filter. See if you can figure out how.
Basically I have vectors within vectors, within vectors, and those deepest vectors contain two coordinate points. for example
[[[3 4] [4 5]] [[5 6] [6 7]]]
I want to check to see if a certain x and y value match any of the coordinate points inside, and if they do, return -1. I tried doing this but the function isn't working.
(defn check-for-stuff
[vect x y]
(if (not (empty? vect))
(dotimes [n (count vect)]
(if (not (empty? (vect n)))
(dotimes [p (count (vect n))]
(if (and (= (((vect n) p) 0) x)
(= (((vect n) p) 1) y))
-1
))))))
For a literal answer to the question, this is my first top-of-head attempt:
(defn check-for-stuff [vect x y]
(when (some (fn [v] (some #(= % [x y]) v)) vect)
-1))
Observed values in testing:
(check-for-stuff [[[1 2] [3 4]]] 1 2)
-1
(check-for-stuff [[[1 2] [3 4]]] 1 3)
nil
That said -- the above is bad practice, since it needs to iterate through the vectors provided (and thus having O(n) performance), rather than being able to do a constant-time membership check as a hash-map or set can.
Also, it would be more conventional to return a more meaningful value for a truthy result, or true if no such meaningful value exists.
#CharlesDuffy is right on the money about this not being the ideal structure for something like this. Based on your description of what you're doing, I would recommend a set of sets of x-y vectors (representing points). For example:
#{#{[3 4] [4 5]} #{[5 6] [6 7]}}
This is a set that represents 2 planes, each represented as a set of x-y vectors. To determine whether any of these sets contains a given x-y point, you can use some and contains?, like this:
(defn check-for-stuff [planes x y]
(some #(contains? % [x y]) planes))
As #CharlesDuffy also pointed out, -1 might not be the best value to use as a return value. The idiomatic thing to do in Clojure when you're writing a function that checks inside a collection for a specific value and tells you whether it's in there or not, is to take advantage of the way that "truthiness" works in Clojure. Every value is considered "truthy" except for false and nil. In the function above, some returns either the plane containing [x y] if it exists in planes, or nil. You can use the return value of this function just like it were returning true or false, like this:
(if (check-for-stuff #{#{[3 4] [4 5]} #{[5 6] [6 7]}} 4 5)
(println "point found")
(println "point not found"))
Assume that a two-dimensional matrix is represented as a vector of
vectors, such that the innermost vectors each represent a row in the
matrix . A two-dimensional matrix is square if the number of rows is equal
to the number of columns.
Why the loop-recur constraint?
If you can assume every row is the same size (regular structure), this would work:
(defn is-square [m]
(= (count m) (count (first m))))
If you want to check every row:
(defn is-square [m]
(apply = (count m) (map count m)))
If you really really want to use loop-recur for some reason:
(defn is-square [m]
(loop [[row & more] m]
(if row
(if (= (count row) (count m))
(recur more)
false)
true)))
I'm starting out with Clojure and, despite having an understanding of recursion, am having trouble thinking of the "right" way to build a lazy-seq for the following function:
I want to build a list of all the frequencies starting from middle C. My first element would be 120 (the frequency of middle C). To get the second element, I'd multiply the first element, 120, by 1.059463 to get 127.13556. To the get the third I'd multiply the second element, 127.13556, by 1.059463, etc etc...
What's the best way to do this in Clojure?
You can use the iterate function for that.
(iterate #(* % 1.059463) 120)
If you are planning to expand this into something more complicated, then you would create a function that recursive calls itself inside a call to lazy-seq. (This is what iterate does internally.)
(defn increasing-frequencies
([] (increasing-frequencies 120))
([freq]
(cons freq (lazy-seq (increasing-frequencies (* freq 1.059463))))))
(nth (increasing-frequencies) 2) ;; => 134.69542180428002
If you start to use this in a tight loop, you may also want to generate a chunked lazy seq. This will pre-calculate the next few elements, instead of one by one.
(defn chunked-increasing-frequencies
([] (chunked-increasing-frequencies 120))
([freq]
(lazy-seq
(let [b (chunk-buffer 32)]
(loop [i freq c 0]
(if (< c 32)
(do
(chunk-append b i)
(recur (* i 1.059463) (inc c)))
(chunk-cons (chunk b) (chunked-increasing-frequencies i))))))))
Note: I would advise against doing this until you have measured a performance problem related to calculating individual elements.
(defn get-frequencies []
(iterate #(* 1.059463 %) 120))
See iterate
Or, if you want to use lazy-seq explicitly, you can do this:
(defn get-frequencies-hard []
(cons
120
(lazy-seq
(map #(* 1.059463 %) (get-frequencies-hard)))))
Which will cons 120 to a lazy seq of every value applied to the map function.
If I understand correctly Clojure can return lists (as in other Lisps) but also vectors and sets.
What I don't really get is why there's not always a collection that is returned.
For example if I take the following code:
(loop [x 128]
(when (> x 1)
(println x)
(recur (/ x 2))))
It does print 128 64 32 16 8 4 2. But that's only because println is called and println has the side-effect (?) of printing something.
So I tried replacing it with this (removing the println):
(loop [x 128]
(when (> x 1)
x
(recur (/ x 2))))
And I was expecting to get some collecting (supposedly a list), like this:
(128 64 32 16 8 4 2)
but instead I'm getting nil.
I don't understand which determines what creates a collection and what doesn't and how you switch from one to the other. Also, seen that Clojure somehow encourages a "functional" way of programming, aren't you supposed to nearly always return collections?
Why are so many functions that apparently do not return any collection? And what would be an idiomatic way to make these return collections?
For example, how would I solve the above problem by first constructing a collection and then iterating (?) in an idiomatic way other the resulting list/vector?
First I don't know how to transform the loop so that it produces something else than nil and then I tried the following:
(reduce println '(1 2 3))
But it prints "1 2nil 3nil" instead of the "1 2 3nil" I was expecting.
I realize this is basic stuff but I'm just starting and I'm obviously missing basic stuff here.
(P.S.: retag appropriately, I don't know which terms I should use here)
A few other comments have pointed out that when doesn't really work like if - but I don't think that's really your question.
The loop and recur forms create an iteration - like a for loop in other languages. In this case, when you are printing, it is indeed just for the side effects. If you want to return a sequence, then you'll need to build one:
(loop [x 128
acc []]
(if (< x 1)
acc
(recur (/ x 2)
(cons x acc))))
=> (1 2 4 8 16 32 64 128)
In this case, I replaced the spot where you were calling printf with a recur and a form that adds x to the front of that accumulator. In the case that x is less than 1, the code returns the accumulator - and thus a sequence. If you want to add to the end of the vector instead of the front, change it to conj:
(loop [x 128
acc []]
(if (< x 1)
acc
(recur (/ x 2)
(conj acc x))))
=> [128 64 32 16 8 4 2 1]
You were getting nil because that was the result of your expression -- what the final println returned.
Does all this make sense?
reduce is not quite the same thing -- it is used to reduce a list by repeatedly applying a binary function (a function that takes 2 arguments) to either an initial value and the first element of a sequence, or the first two elements of the sequence for the first iteration, then subsequent iterations are passed the result of the previous iteration and the next value from the sequence. Some examples may help:
(reduce + [1 2 3 4])
10
This executes the following:
(+ 1 2) => 3
(+ 3 3) => 6
(+ 6 4) => 10
Reduce will result in whatever the final result is from the binary function being executed -- in this case we're reducing the numbers in the sequence into the sum of all the elements.
You can also supply an initial value:
(reduce + 5 [1 2 3 4])
15
Which executes the following:
(+ 5 1) => 6
(+ 6 2) => 8
(+ 8 3) => 11
(+ 11 4) => 15
HTH,
Kyle
The generalized abstraction over collection is called a sequence in Clojure and many data structure implement this abstraction so that you can use all sequence related operations on those data structure without thinking about which data structure is being passed to your function(s).
As far as the sample code is concerned - the loop, recur is for recursion - so basically any problem that you want to solve using recursion can be solved using it, classic example being factorial. Although you can create a vector/list using loop - by using the accumulator as a vector and keep appending items to it and in the exist condition of recursion returning the accumulated vector - but you can use reductions and take-while functions to do so as shown below. This will return a lazy sequence.
Ex:
(take-while #(> % 1) (reductions (fn [s _] (/ s 2)) 128 (range)))