0
votes

Hi I'm currently trying to use the elem function in prelude.

data MyType = A Int
            | B Int Int
            | C Int
            | D Int Int
     deriving (Show,Eq)

list = [ A _, B _ _ ]    

or

list = [ A Int, B Int Int ]

bool = (A 12) elem list  -- use like this to get a Boolean value.

The problem is the list, it will (both) have compile error. Can someone tell me the right way to define list?

Oops about the data and deriving (Show,Eq) in my main code I did do all that. The reason for this question is that I have a big list of MyType and I want to cherry pick one or two of the types out of the big list modify it then put it back, how do I do that? Exp. bigList=[ A 3, C 6, A 5, B 5 8, D 5 6 ] I would like to pick out only the data type ( A Int ) and (B Int Int) , maybe change all value for the two data type into 0, after modification put back so I end up with a new list. newBigList=[ A 0, C 6, A 0, B 0 0, D 5 6 ]

Thanks

1
What did you try? the above isn't valid Haskell.Don Stewart

1 Answers

7
votes

First of all, it is data and not Data. Second, you are mixing type variables (Int) with values in defining list, while _ can only be used in pattern matching. You should write this instead to build a list of type [MyType]:

list = [A 12, B 1 5]

Third, your declaration for bool uses elem :: Eq a => a -> [a] -> Bool as an infix operator, while it is a function like any other. Write either

bool = elem (A 12) list

or

bool = (A 12) `elem` list

As you see from the type signature of elem, you need to derive the Eq typeclass. It could be useful to be able to print your MyType values also, so you may consider adding deriving (Eq,Show) at the end of your type declaration.

It seems like you're mistaking Haskell for Prolog. Haskell do not work by unification like Prolog. You should start reading a good tutorial or book from the basics.