Reputation: 553
I have a data type:
data Numbers = Numbers {a::Int, b::Int}
How can I construct [Numbers]
in order to get the same effect as
[[a,b] | a <- [1,2], b <- (filter (/=a) [1,2])]
so the result will be similar to [[1,2],[2,1]]
Upvotes: 0
Views: 1077
Reputation: 1
This seems to be nothing but a selection with removal. You can find efficient code to do that in an older question.
If it's certainly about exactly two elements, then this implementation will be efficient:
do x:ys <- tails [1..3]
y <- ys
[(x, y), (y, x)]
Upvotes: 0
Reputation: 5417
You have to use Numbers
as the constructor (note: []
is also a constructor, only with a specific syntax sugar, so there is no fundamental difference).
data Numbers = Numbers {a::Int, b::Int}
deriving Show
main = print [ Numbers a b | a <- [1, 2], b <- filter (/=a) [1, 2] ]
> main
[Numbers {a = 1, b = 2},Numbers {a = 2, b = 1}]
Upvotes: 2