Clojure Speccing a natural number - clojure

A natural number is a non-negative integer. How would you express that with Clojure Spec?

This is already a predicate function in 1.9 which matches fixed precision non-negative integers:
(s/valid? nat-int? 1)
; true
Note however that this does not match arbitrary precision integers like bigints:
(s/valid? nat-int? (bigint 1))
; false

There's also the spec/int-in function which allows you to specify a range like
(spec/def ::natural-number
(spec/int-in 0 Integer/MAX_VALUE))
(spec/exercise ::natural-number)
=> ([1 1] [1 1] [0 0] [0 0] [1 1] [3 3] [4 4] [4 4] [50 50] [1 1])
Note however that spec/int-in does not match arbitrary precision integers like bigint:
(spec/valid? (spec/int-in 0 Integer/MAX_VALUE) (bigint 1))
=> false

You could express it as a compound of the integer? predicate and whether it's larger than 0 or not.
(spec/def ::natural-number
(spec/and integer? (partial <= 0)))
(spec/exercise ::natural-number)
=> ([0 0] [0 0] [0 0] [1 1] [5 5] [5 5] [0 0] [0 0] [0 0] [19 19])
This matches both fixed and arbitrary precision integers:
(spec/valid? ::natural-number (long 0))
=> true
(spec/valid? ::natural-number (int 0))
=> true
(spec/valid? ::natural-number (bigint 0))
=> true

Related

clojure-spec: Unable to get function's postcondition right

I'm trying clojure spec on a simple function that computes the "neighbours" of a (row,col) position in a square matrix. For example for the 4x4 matrix given below, the neighbours of cell (1,1) shall be: (0,1), (1,0), (1,2), (2,1). The neighbours of cell (4,3), which is not even in the matrix' range, shall be (3,3) etc.
The function's input is the size of the matrix and the (row,col) of the position of interest. The output is a collection of (row,col) of the neighbours. This collection can be empty if there are no neighbours.
This problem can be found in "The Joy of Clojure, 2nd editions, page 94; but this code is modified because the original was too compact for me. Then I tried to spec it and check the spec in the :pre and :post parts.
However, I don't get the :post part to work. When I run the test cases, I get:
java.lang.ClassCastException: java.lang.Boolean cannot be cast
to clojure.lang.IFn
What to change?
(require '[clojure.spec.alpha :as s]
'[clojure.test :as t])
; ===
; Specs
; ===
(s/def ::be-row-col
(s/coll-of integer? :count 2 :kind sequential?))
(s/def ::be-square-matrix-size
(s/and integer? #(<= 0 %)))
(s/def ::be-row-col-vector
(s/and (s/coll-of ::be-row-col) (s/int-in-range? 0 5 #(count %))))
; ===
; Function of interest
; ===
(defn neighbors [sqmsz rc]
{:pre [(s/valid? ::be-row-col rc)
(s/valid? ::be-square-matrix-size sqmsz)]
:post [(s/valid? ::be-row-col-vector %)]
}
(let [ cross [[-1 0] [1 0] [0 -1] [0 1]]
in-sq-matrix? (fn [x]
(and (<= 0 x) (< x sqmsz)))
in-sq-matrix-rc? (fn [rc]
(every? in-sq-matrix? rc))
add-two-rc (fn [rc1 rc2]
(vec (map + rc1 rc2)))
get-rc-neighbors (fn [rc]
(map (partial add-two-rc rc) cross)) ]
(filter in-sq-matrix-rc? (get-rc-neighbors rc))))
; ===
; Put a collection of [row col] into an expected form
; ===
; this is used to run the test code
(defn formify [rc-coll]
(let [ cmp (fn [rc1 rc2]
(let [ [r1 c1] rc1
[r2 c2] rc2 ]
(cond (< r1 r2) -1 ; sort by row
(> r1 r2) +1
(< c1 c2) -1 ; then by column
(> c1 c2) +1
true 0))) ]
(vec (sort cmp rc-coll))))
; ===
; Testing
; ===
(defn test-nb [ sqmsz rc expected txt ]
(do
(t/is (= (formify (neighbors sqmsz rc)) expected) txt)
))
(test-nb 0 [0 0] [] "Zero-size matrix, outside #1")
(test-nb 0 [1 1] [] "Zero-size matrix, outside #2")
(test-nb 1 [0 0] [] "One-size matrix, inside")
(test-nb 1 [1 0] [[0 0]] "One-size matrix, outside")
(test-nb 5 [0 0] [[0 1] [1 0]] "Testing top left")
(test-nb 5 [1 0] [[0 0] [1 1] [2 0]] "Testing left edge")
(test-nb 5 [1 1] [[0 1] [1 0] [1 2] [2 1]] "Testing middle #1")
(test-nb 5 [2 2] [[1 2] [2 1] [2 3] [3 2]] "Testing middle #2")
(test-nb 5 [3 3] [[2 3] [3 2] [3 4] [4 3]] "Testing middle #3")
(test-nb 5 [4 4] [[3 4] [4 3]] "Testing btm right")
(test-nb 5 [5 5] [] "Testing outside #1")
(test-nb 5 [5 4] [[4 4]] "Testing outside #2")
(test-nb 5 [4 3] [[3 3] [4 2] [4 4]] "Testing btm edge")
You're just missing the # prefix to make your anonymous function in the :post condition. The post condition needs to be a function that can take the output of the subject function's invocation.
:post [#(s/valid? ::be-row-col-vector %)]
Could also be rewritten as:
:post [(fn [o] (s/valid? ::be-row-col-vector o))]
But depending on your use case, you may want to look into function specs and instrument as an alternative to :pre and :post conditions. I wrote more examples here.

Clojure - Unknown number of arguments in a function

I have a function
(defn x [w]
(let [[w1 w2 w3] w]
(println w1)
(println w2)
(println w3)))
If I call the function
(x [[1 1] [2 2] [3 3]])
=> [1 1]
[2 2]
[3 3]
which is what I expect
Is there a way to generalise this? In this case I knew that w was a vector containing 3 vectors so I know to have [w1 w2 w3] If w was then a vector of 4 vectors, the last vector would not be set to anything
What I want is where w is a vector of n vectors and then in the let of the function set them to [w1 w2 w3 ... wn]? (note doesn't necessarily have to be w1, w2, ... wn)
The println are just there for debugging so not that important for the function
Any help would be much appreciated.
(defn x [ws]
(dorun (map println ws)))
For example,
(x [[1 1] [2 2] [3 3]])
[1 1]
[2 2]
[3 3]
=> nil
The map applies println to each of the ws in turn, returning
the nil results as a sequence, on demand (lazily).
The dorun demands the whole sequence, discarding it as it goes,
returning nil.
If you want to see the sequence, replace dorun with doall:
(defn x [ws]
(doall (map println ws)))
=> (x [[1 1] [2 2] [3 3]])
[1 1]
[2 2]
[3 3]
=> (nil nil nil)
A more concise alternative to the former is
(defn x [ws]
(doseq [w ws] (println w)))
... and to the latter is
(defn x [ws]
(for [w ws] (println w)))

Clojure: how to test if a seq is a "subseq" of another seq

Is there an easy / idiomatic way in Clojure to test whether a given sequence is included within another sequence? Something like:
(subseq? [4 5 6] (range 10)) ;=> true
(subseq? [4 6 5] (range 10)) ;=> false
(subseq? "hound" "greyhound") ;=> true
(where subseq? is a theoretical function that would do what I'm describing)
It seems that there is no such function in the core or other Clojure libraries... assuming that's true, is there a relatively simple way to implement such a function?
(defn subseq? [a b]
(some #{a} (partition (count a) 1 b)))
(defn subseq? [target source]
(pos? (java.util.Collections/indexOfSubList (seq source) (seq target))))
***
DISCLAIMER EDIT
This proposal is not reliable for reasons discussed in comments section.
***
#amalloy 's solution has one flaw - it won't work with infinite lazy sequences. So it will loop forever when you run this:
(subseq? [1 2 3] (cycle [2 3 1]))
I propose this implementation to fix this:
(defn- safe-b
"In case b is a cycle, take only two full cycles -1 of a-count
to prevent infinite loops yet still guarantee finding potential solution."
[b a-count]
(take
(* 2 a-count)
b))
(defn subseq? [a b]
(let [a-count (count a)]
(some #{a} (partition a-count 1 (safe-b b a-count)))))
=> #'user/safe-b
=> #'user/subseq?
(subseq? [1 2 3] (cycle [2 3 1]))
=> [1 2 3]
(subseq? [1 2 3] (cycle [3 2 1]))
=> nil
(subseq? [1 2 3] [2 3])
=> nil
(subseq? [2 3] [1 2 3])
=> [2 3]

Circularly shifting nested vectors

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]]

Compare two vectors in clojure no matter the order of the items

I want to compare two vectors and find out if the items they have are the same no matter the order the items are in.
So..
right now in clojure:
(= [1 2 3] [3 2 1]) ;=> false
I want:
(other_fun [1 2 3] [3 2 1]) ;=> true
(other_fun [1 2 3 4] [3 2 1]) ;=> false
I could not find a containsAll like in java
If you do care about duplicates, you can compare their frequency maps. These are maps with each collection element as a key and number of occurrences as a value. You create them using standard function frequencies, like in given examples.
Different order, same number of duplicates:
(= (frequencies [1 1 2 3 4])(frequencies [4 1 1 2 3]))
evaluates true.
Different order, different number of duplicates:
(= (frequencies [1 1 2 3 4])(frequencies [4 1 2 3]))
evaluates false.
So, you can write a function:
(defn other_fun [& colls]
(apply = (map frequencies colls)))
If you don't care about duplicates, you could create sets from both vectors and compare these:
(= (set [1 2 3]) (set [3 2 1])) ;=> true
As a function:
(defn set= [& vectors] (apply = (map set vectors)))
If you don't care about duplicates, other answers a perfectly applicable and efficient.
But if you do care about duplicates, probably the easiest way to compare two vectors is sorting and comparing:
user=> (= (sort [3 5 2 2]) (sort [2 2 5 3]))
true
user=> (= (sort [3 5 2 2]) (sort [2 5 3]))
false
Create sets from them:
user=> (= (set [1 2 3]) (set [3 2 1]))
true
user=> (defn other_func [col1 col2]
(= (set col1) (set col2)))
#'user/other_func
user=> (other_func [1 2 3] [3 2 1])
true
You're on the JVM already, so if you want containsAll, then just use containsAll, right?
(defn other_fun
"checkes the presence of the elements of vec1 in vec2 and vice versa"
[vec1 vec2]
(if (or (some nil?
(for [a vec1 b [vec2]] (some #(= % a) b)))
(some nil?
(for [a vec2 b [vec1]] (some #(= % a) b))))
false
true))
(other_fun [1 2 3] [3 2 1]) ;=> true
(other_fun [1 2 3 4] [3 2 1]) ;=> false