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

2 Answers 2

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}]
Sign up to request clarification or add additional context in comments.

3 Comments

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]]
@Z.pyyyy, yes, sort of, x = [Numbers a b | a <- [1..100], b <- filter (/= a) [1..100]].
@Z.pyyyy Read some haskell turorial like YAHT or real world haskell.
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)]

1 Comment

I think the question's quite clear that it's about more than two elements, but yes, that works in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.