How to make list comprehension in Clojure?

I am studying Clojure and I have found a solution to find the problem of a regular triangle in a Haskell book using list comprehension so that the problem is solved neatly:

Finding the Right Triangle

  • The lengths of the three sides are integers.

  • Each side is less than or equal to 10.

  • Along the perimeter of the triangles (the sum of the lateral lengths) is 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?

+6
source share
2 answers

Clojure has for syntax:

 (for [ c (range 1 (inc 10)) a (range 1 (inc c)) b (range 1 (inc a)) :when (== (+ (* aa) (* bb)) (* cc)) :when (== (+ abc) 24) ] [abc]) 
+12
source
 (for [c (range 1 11) a (range 1 c) b (range 1 a) :when (and (= (+ abc) 24) (= (* cc) (+ (* aa) (* bb))))] [abc]) 

You can also improve performance in honest bits by inserting :let [c2 (* cc)] between the a and b bindings, and then use c2 in :when to avoid squaring c more often than necessary.

Clojure for is basically a do-notation for the list monad, with :when acting like guard and :let , acting like let . There :while too, but I don't know what haskell is the thing that matches.

+8
source

Source: https://habr.com/ru/post/969673/


All Articles