In: Computer Science
In Clojure, how do I enter a vector of vectors and print the specified index in each vector? i.e. I enter [1 2 3 4] [5 6 7 8] and my function gives me [1 5] when I call (index vector 0)?
check out the solution and do COMMENT if any doubts.
-----------------------------------------------------------------
(ns clojure.examples.program1
(:gen-class))
(defn index [v n]
(def cnt (count v)) ; count the number of vectors present in 'v'
and store it in 'cnt'
(loop [i 0 mat []] ; loop begins from i=0 and an empty vector
called 'mat'
(if (< i cnt) ; check if i < cnt
(recur (inc i) (conj mat (get-in v [i n]))) ; increment i and get
the specified indexed element 'n' of vector 'v' and concat to
vector 'mat' using 'conj'
(println mat)))) ; print the final vector as resultant
; the below is the way to enter vector of vectors
(def vect [[1 2 3 4] [5 6 7 8]])
; pass the defined vector of vectors 'vect' and index '0' to
function 'index'
; call #1
(index vect 0)
; call #2
(index vect 2)
--------------------------------------------------------------------------------------------------------
---
OUTPUT ::