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?
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With