0

I don't get why the combination of every? and identity is giving different results in the following two examples. It seems that it gives the expected answer upon calling it on true false collections, but not with the numbers and strings:

(every? identity [1 2 3 4])=> true

(every? identity [true true false])=> false

Nathan Davis
  • 5,636
  • 27
  • 39
  • What results are you expecting? – Nathan Davis Sep 03 '15 at 04:21
  • i was thinking that identity passes the args of the coll every time to `every?` and `every?` checks the truthy value of them, goes through the coll and returns true if all of the args have had the same truthy value as the first one. So `every?` doesn't force `identity` to pass the truthy value of the other arguments as `every?` walks through the coll? –  Sep 03 '15 at 09:32

2 Answers2

4

It makes sense in your latter case that every? would return false since one of the elements in the tested collection is false; i.e.:

=> (identity false)
false

As every? works its way across the vector and encounters the above application, it sees a falsy value, so returns such.

=> (doc every?)
-------------------------
clojure.core/every?
([pred coll])
  Returns true if (pred x) is logical true for every x in coll, else
  false.
Micah Elliott
  • 9,600
  • 5
  • 51
  • 54
  • In case of true false arguments i can see the logic, but with the numbers `identity` returns the number itself which is java.lang.Long, not a truthy value. Hence i thought it would be rather equal to `(every? #(= % 1) [1 2 3 4])`. What is confusing for me is that: identity returns the first argument it gets from the coll, passes it as the predicate to `every?` and then every? checks every of the rest arguments against that first argument? `(every? identity [false true true])` returns also `false`, does that mean every? checks the first value passed to it by identity against the others? –  Sep 03 '15 at 09:44
  • @AmirTeymuri, in Clojure every value is "truthy" except for `false` and `nil`. See http://stackoverflow.com/q/5830571/2472391. – galdre Sep 03 '15 at 13:46
  • @AmirTeymuri — No, `identity` is not applied to just the first element. `every?` applied the predicate (in this case, `identity`) is applied to *each* element in the collection until either it reaches the end of the collection (in which case `every?` returns `true`) or the predicate (`identity`) returns a "falsey" value (namely, `nil` or `false`), in which case `every?` returns `false`. – Nathan Davis Sep 03 '15 at 16:45
2

This is from the clojure documentation for every?:

Returns true if (pred x) is logical true for every x in coll, else false.

By evaluating (identity) on the false value inside the array you are getting false because the identity of false is false.

Razvanescu
  • 113
  • 1
  • 1
  • 7