Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected result from reduce function

Tags:

clojure

I would like to get the smallest element from a vector. For this I use combine the reduce and min functions. However, when providing my own implementation of min I get unexpected results:

user=> (reduce (fn [x y] (< x y) x y) [1 2 3 2 1 0 1 2])
2
user=> (reduce min [1 2 3 2 1 0 1 2 3])
0

The reduce with standard min returns 0 as expected. However, when I provide my own implementation it returns 2. What am I doing wrong?

like image 527
StackedCrooked Avatar asked May 11 '10 22:05

StackedCrooked


1 Answers

You're missing an if:

(reduce (fn [x y] (if (< x y) x y)) ...)
                   ^-- note the if

works fine. :-)

like image 106
Michał Marczyk Avatar answered Oct 12 '22 05:10

Michał Marczyk