0

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]]

Mischa Arefiev
  • 5,227
  • 4
  • 26
  • 34
PinkiePie-Z
  • 525
  • 1
  • 6
  • 28

2 Answers2

2

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}]
Mischa Arefiev
  • 5,227
  • 4
  • 26
  • 34
  • if it is a really big list, like a<-[1..100] b<-[1..100], how can i implement it in a hs file ? can i do sth like [Numbers] = [Numbers a b | a<-[1..100], b<- filter (/=a) [1..100]] – PinkiePie-Z Sep 20 '12 at 08:38
  • @Z.pyyyy, yes, sort of, `x = [Numbers a b | a <- [1..100], b <- filter (/= a) [1..100]]`. – huon Sep 20 '12 at 08:43
  • @Z.pyyyy Read some haskell turorial like YAHT or real world haskell. – Satvik Sep 20 '12 at 09:25
0

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)]
Community
  • 1
  • 1
ertes
  • 1
  • I think the question's quite clear that it's about more than two elements, but yes, that works in this case. – AndrewC Sep 20 '12 at 09:35