This is hard to explain but easy to show. Not sure why I haven't figured it out myself, so I must be missing something in clojure that is obvious.
I need to combine a vector with itself, into a vector, and I need to combine the first element with all the remaining elements, then the 2nd element, with all the remaining elements (3rd and after).
As a short example:
[1 2 3 4 5]
I need a function to get:
[[1 2] [1 3] [1 4] [1 5] [2 3] [2 4] [2 5] [3 4] [3 5]]
If this looks like getting half the pairs for a large matrix, you are right. I only want to solve half the matrix minus the middle diagonal. This is the only part I need to be sequential(so I only solve half) and the rest I want to use the reducers library to parallelize the heavier math in the background.
Thanks in advance!
What you want is built into clojure/math.combinatorics:
https://github.com/clojure/math.combinatorics
The basic example you are looking for is on the readme, but for completeness to this answer, I'll repeat it here:
(ns example.core
(:require [clojure.math.combinatorics :as combo]))
(combo/combinations [1 2 3] 2)
;;=> ((1 2) (1 3) (2 3))
I'd just use a for :
(for [ i (range 1 6) j (range 6) :when (< i j)] [i j])
; => ([1 2] [1 3] [1 4] [1 5] [2 3] [2 4] [2 5] [3 4] [3 5] [4 5])
(def v [1 2 3 4 5])
(for [i (range (count v))
:let [vv (drop i v)]
r (rest vv)]
[(first vv) r])
=> ([1 2] [1 3] [1 4] [1 5] [2 3] [2 4] [2 5] [3 4] [3 5] [4 5])
Related
I have a function
(defn my-fn [a b & args]
[a
(for [arg args]
(into [] (butlast arg)))
b])
If I do (my-fn [1 2] [3 4] [5 6 2] [7 8 3])
It returns [[1 2] ([5 6] [7 8]) [3 4]]
I want the output to be [[1 2] [5 6] [7 8] [3 4]] but I cannot figure out how to do this
Any help would be much appreciated.
I'd into [a] all your mapped values and then conj b at the end. E.g.
(defn my-fn [a b & args]
(-> [a]
(into (map (comp vec butlast) args))
(conj b)))
and one more variant, using quote and unquote splicing:
user> (defn my-fn2 [a b & args]
`[~a ~#(map (comp vec butlast) args) ~b])
;;=> #'user/my-fn2
user> (my-fn2 [1 2] [3 4] [5 6 2] [7 8 3])
;;=> [[1 2] [5 6] [7 8] [3 4]]
Your for statement returns a list.
(defn my-fn [a b & args]
(->> [[a]
(map (comp vec butlast) args)
[b]]
(apply concat)
vec))
The final vec transform your seq into a vector.
Here is one solution:
(defn my-fn [a b & args]
(vec
(concat
[a]
(for [arg args]
(into [] (butlast arg)))
[b])))
(my-fn [1 2] [3 4] [5 6 2] [7 8 3])
=> [[1 2] [5 6] [7 8] [3 4]]
Please note that concat returns a lazy list, which for larger and/or more complicated problems can cause a StackOverflowException. The outer vec converts the lazy list in to a concrete vector. It is unnecessary for this example and you could remove it if you want.
As another note, concat expects each argument to be a list/vector, so I have wrapped a and b into 1-element vectors. The output of for is already a (lazy) list.
Because conj, cons, concat, etc can be somewhat non-intuitive in their behavior, you may wish to checkout the helper functions glue, append, prepend, & friends in the Tupelo library.
Background
Suppose we have a mixture of scalars & vectors (or lists) that we want to combine into a single vector. We want a function ??? to give us the following result:
(??? 1 2 3 [4 5 6] 7 8 9) => [1 2 3 4 5 6 7 8 9]
Clojure doesn’t have a function for this. Instead we need to wrap all of the scalars into vectors and then use glue or concat:
; can wrap individually or in groups
(glue [1 2 3] [4 5 6] [7 8 9]) => [1 2 3 4 5 6 7 8 9] ; could also use concat
(glue [1] [2] [3] [4 5 6] [7] [8] [9]) => [1 2 3 4 5 6 7 8 9] ; could also use concat
It may be inconvenient to always wrap the scalar values into vectors just to combine them with an occasional vector value. Instead, it might be more convenient to unwrap the vector values, then combine the result with other scalars. We can do that with the ->vector and unwrap functions:
(->vector 1 2 3 4 5 6 7 8 9) => [1 2 3 4 5 6 7 8 9]
(->vector 1 (unwrap [2 3 4 5 6 7 8]) 9) => [1 2 3 4 5 6 7 8 9]
It will also work recursively for nested unwrap calls:
(->vector 1 (unwrap [2 3 (unwrap [4 5 6]) 7 8]) 9) => [1 2 3 4 5 6 7 8 9]
Alternate Solution Using Python-Style Generator Functions
You could also solve it this way:
(ns tst.clj.core
(:use clj.core tupelo.test)
(:require [tupelo.core :as t] ))
(t/refer-tupelo)
(defn my-fn [a b & args]
(lazy-gen
(yield a)
(yield-all (for [arg args]
(into [] (butlast arg))))
(yield b)))
(my-fn [1 2] [3 4] [5 6 2] [7 8 3]) => ([1 2] [5 6] [7 8] [3 4])
Here lazy-gen creates a context for a "generator function", where successive values are added to the output list using the yield and yield-all functions. Note that the yield-all function is like the Clojure "unquote-splicing" operator ~# and "unwraps" its sequence into the output stream.
An even easier answer is to dive deeper into the for part of your original solution to apply the yield output tap:
(defn my-fn2 [a b & args]
(lazy-gen
(yield a)
(doseq [arg args]
(yield (butlast arg)))
(yield b)))
(my-fn2 [1 2] [3 4] [5 6 2] [7 8 3]) => ([1 2] (5 6) (7 8) [3 4])
This version of the solution follows your original logic more closely,
and avoids the accidental complexity of the for function wrapping its results into a sequence, which conflicts with the a and b values not being wrapped in a vector. We also no longer need the (into [] ...) part of the original function.
Note that we have replaced the for with doseq since:
We are no longer using the return value of the loop
And, therefore, a lazy solution would never run
This question already has answers here:
Clojure - Splitting a vector
(3 answers)
Closed 5 years ago.
How can I combine [[1 2] [3 4]] and [5 6] to get [[1 5] [2 5] [3 6] [4 6]]
I tried (map vector [[1 2] [3 4]] [5 6]) but the result was ([[1 2] 5] [[3 4] 6])
Any help would be much appreciated. Thanks
You can use mapcat and an inner map like this:
user=> (mapcat (fn [as b]
(mapv #(vector % b) as))
[[1 2] [3 4]] [5 6])
([1 5] [2 5] [3 6] [4 6])
If I have two arguments [[1 2] [3 4]] and [5 6], how can I get to [[1 5] [2 6] [3 5] [4 6]].
I thought I may have to use for so I tried,
(for [x [[1 2] [3 4]]]
(for [xx x]
(for [y [5 6]] [xx y])))
But it returned ((([1 5] [1 6]) ([2 5] [2 6])) (([3 5] [3 6]) ([4 5] [4 6])))
Any help would be much appreciated. Thanks
(mapcat #(map vector % [5 6]) [[1 2] [3 4]])
or using for:
(for [c [[1 2] [3 4]]
p (map vector c [5 6])]
p)
If I understood your question correctly, your solution is actually very close. You did not need to nest the for expressions explicitly, since doing so creates a new list at every level, instead, just use multiple bindings:
(for [x [[1 2][3 4]]
xx x
y [5 6]]
[xx y])
Which will result in
([1 5] [1 6] [2 5] [2 6] [3 5] [3 6] [4 5] [4 6])
Edit
Now that I finally read your question carefully, I came up with the same answer as #Lee did (mapcat (fn[x] (map vector x [5 6])) [[1 2] [3 4]]), which is the right one and should probably be accepted.
This is one (hmm - not particularly elegant) way to get your answer, without using for:
(defn f [x y]
(let [x' (apply concat x)
multiples (/ (count x') (count y))
y' (apply concat (repeat multiples y))]
(mapv vector x' y')))
(f [[1 2] [3 4]] [5 6])
;;=> [[1 5] [2 6] [3 5] [4 6]]
Given a nested vector A
[[1 2 3] [4 5 6] [7 8 9]]
my goal is to circularly shift rows and columns.
If I first consider a single row shift I'd expect
[[7 8 9] [1 2 3] [4 5 6]]
where the 3rd row maps to the first in this case.
This is implemented by the code
(defn circles [x i j]
(swap-rows x i j))
with inputs
(circles [[1 2 3] [4 5 6] [7 8 9]] 0 1)
However, I am unsure how to go further and shift columns. Ideally, I would like to add to the function circles and be able to either shift rows or columns. Although I'm not sure if it's easiest to just have two distinct functions for each shift choice.
(defn circles [xs i j]
(letfn [(shift [v n]
(let [n (- (count v) n)]
(vec (concat (subvec v n) (subvec v 0 n)))))]
(let [ys (map #(shift % i) xs)
j (- (count xs) j)]
(vec (concat (drop j ys) (take j ys))))))
Example:
(circles [[1 2 3] [4 5 6] [7 8 9]] 1 1)
;= [[9 7 8] [3 1 2] [6 4 5]]
Depending on how often you expect to perform this operation, the sizes of the input vectors and the shifts to be applied, using core.rrb-vector could make sense. clojure.core.rrb-vector/catvec is the relevant function (you could also use clojure.core.rrb-vector/subvec for slicing, but actually here it's fine to use the regular subvec from clojure.core, as catvec will perform its own conversion).
You can also use cycle:
(defn circle-drop [i coll]
(->> coll
cycle
(drop i)
(take (count coll))
vec))
(defn circles [coll i j]
(let [n (count coll)
i (- n i)
j (- n j)]
(->> coll
(map #(circle-drop i %))
(circle-drop j))))
(circles [[1 2 3] [4 5 6] [7 8 9]] 2 1)
;; => [[8 9 7] [2 3 1] [5 6 4]]
There's a function for that called rotate in core.matrix (as is often the case for general purpose array/matrix operations)
The second parameter to rotate lets you choose the dimension to rotate around (0 for rows, 1 for columns)
(use 'clojure.core.matrix)
(def A [[1 2 3] [4 5 6] [7 8 9]])
(rotate A 0 1)
=> [[4 5 6] [7 8 9] [1 2 3]]
(rotate A 1 1)
=> [[2 3 1] [5 6 4] [8 9 7]]
I tried this in core.logic
(require [clojure.core.logic :as l])
(l/run* [q]
(l/fresh [a b c]
(l/membero a [1])
(l/membero b [4 5])
(l/membero c [1 2])
(l/== q [a b])))
expecting the result to be [1 4] [1 5]
but it was [1 4] [1 4] [1 5] [1 5]
then I started playing with it and found this:
(require [clojure.core.logic :as l])
(l/run* [q]
(l/fresh [a b c]
(l/membero a [1])
(l/membero b [4 5])
(l/membero c [1 1 1 1 1 1 1 1])
(l/== q [a b])))
;; => ([1 4] [1 4] [1 4] [1 5] [1 4] [1 4] [1 5] [1 4] [1 5] [1 4] [1 5] [1 5] [1 5] [1 5])
where there is a [1 5] interspersed with [1 4]
what is happening? is this repetition thing supposed to be a feature or a bug?
This is because the usage of the logic variable c which is not required as it is not being unified with q. If you remove c then you will get desired result. Basically you need to understand how the substitution works in core.logic to understand why you are getting these duplicate results because of c.
At a high level the process is like searching a tree for solutions, in this case each element in the vector which is membero with c leads to a node in the search tree and that causes duplicate results because for each node introduced by c probable values leads to correct result as c isn't used in the unification (l/== q [a b])