Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating tuples using list comprehension

Tags:

haskell

I generate tuples using list comprehension:

[(a,b,c) | a <- [1..3], b <- [1..3], c <- [1..3]]

Since all three entries of the tuples are from the same interval, is there a shorter way to write this?

like image 848
Luca9984 Avatar asked Mar 02 '26 00:03

Luca9984


1 Answers

A few alternatives

let xs = [1..3] in [(a,b,c) | a <- xs, b <- xs, c <- xs]
[(a,b,c) | let xs = [1..3], a <- xs, b <- xs, c <- xs]
(,,) <$> [1..3] <*> [1..3] <*> [1..3]
let xs = [1..3] in (,,) <$> xs <*> xs <*> xs
(\[a,b,c]->(a,b,c)) <$> replicateM 3 [1..3]

However, I'd look for the most readable one, rather than the shortest.

like image 84
chi Avatar answered Mar 04 '26 14:03

chi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!