Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do list comprehension in Clojure?

I am learning Clojure, and I found the solution to find the right triangle problem in a Haskell book using list comprehension making the problem neatly solved:

Finding the Right Triangle

  • The lengths of the three sides are all integers.

  • The length of each side is less than or equal to 10.

  • The triangle’s perimeter (the sum of the side lengths) is equal to 24.

In Haskell:

ghci> let rightTriangles' = [ (a,b,c) | c <- [1..10], a <- [1..c], b <- [1..a],
a^2 + b^2 == c^2, a+b+c == 24]

ghci> rightTriangles'
[(6,8,10)]

Is there such an elegant list comprehension solution in Clojure?

like image 679
Nick Avatar asked May 22 '14 02:05

Nick


1 Answers

Clojure has for syntax:

(for [ c (range 1 (inc 10))
       a (range 1 (inc c))
       b (range 1 (inc a))
       :when (== (+ (* a a) (* b b)) 
                 (* c c))
       :when (== (+ a b c) 24) ]
  [a b c])
like image 68
J. Abrahamson Avatar answered Oct 12 '22 04:10

J. Abrahamson