-1

I want to write a program in clojure that would return only the first index value of true values from my function. My code goes here:

 (defn func [f x] (map f x))

So, if I give a value like:

(func zero? [1 1 1 0 3 7 0 2])

It gives me:

(false false false true false false true false)

and if I give:

(func (fn [n] (= n 6)) [:cat :dog :six :blorg 6]) 

It returns:

(false false false false true)

But, what I want is index value of first true. Like for

(func zero? [1 1 1 0 3 7 0 2]) => 3 (desired result)
(func (fn [n] (= n 6)) [:cat :dog :six :blorg 6]) => 4 (desired result)
(func zero? [1 1 3 7 2]) => nil (desired result)

Can anybody suggest how to get the first index value of true?

user227666
  • 734
  • 2
  • 18
  • 34

3 Answers3

1
 (count (take-while not '(false false false true false false true false)))
 => 3

 (.indexOf '(false true) true)
 => 1
guilespi
  • 4,672
  • 1
  • 15
  • 24
  • thanks for your suggestion but it works for only cases where `true` value is present. For cases where `true` is not present like: `(fun nil? [])` is shows `0` whereas it should have shown `nil` as mentioned in my question. Like for `(func zero? [1 1 3 7])` it's returning `4` but it should have returned `nil`, which means when `true` is not present it's just count the number of elements, so it's showing values `0` and `4`. So this is not a correct answer. – user227666 Oct 25 '13 at 14:41
  • no your edited answer returns `-1` given the above cases. I think I have figured out the answer and will post in few minutes after all test cases. – user227666 Oct 25 '13 at 14:53
0

The answer you posted yourself seems slightly overcomplicated. It can be simplified to this:

(defn first-indexed [pred coll]
  (first (keep-indexed (fn [idx itm]
                         (when (pred itm)
                           idx))
                       coll)))

i.e. the true? (vec (map part of tun is unnecessary.

Rörd
  • 6,556
  • 21
  • 27
-1

Ok, so I found out an answer for my question itself:

(defn indices [pred coll]
  (keep-indexed #(when (pred %2) %1) coll))

  (defn tun [f x]
    (first (indices true? 
              (vec (map f x))))) 

and if you do:

(tun zero? [1 1 3 7 2]) => nil (the exact desired result) 
user227666
  • 734
  • 2
  • 18
  • 34