Lethi
Lethi

Reputation: 1177

List containing different types

I am currently writing my own structurewhich can handle ints and strings at the same time:

Something like

data Collection = One Int | Two String | Three(Collection)(Collection)

However, I was trying to write a function which could convert my structure into a list.

Am I right in thinking this is impossible because, by default doing:

[1,2,"test"]

in the console doesn't work and therefore my function is bound to always fail?

Upvotes: 2

Views: 1301

Answers (3)

Aaron McDaid
Aaron McDaid

Reputation: 27183

You should probably just define

type Collection = [Either Int String]

Then, instead of doing

l = [1,2,"test"]

you can do

l :: Collection
l = [Left 1, Left 2, Right "test"]

If you want more than two types, you'll need to define your own member type. So you would do something like this aswell

data MemberType = MyInt Int | MyString String | MyFloat Float deriving Show
type Collection = [MemberType]
l :: Collection
l = [MyInt 1, MyInt 2, MyString "test", MyFloat 2.2]

The deriving Show isn't necessary, but it's nice to be able to simply do print l to print the list in a nice way.

Upvotes: 6

Tom Crockett
Tom Crockett

Reputation: 31619

Your data structure is basically a binary tree which stores either an Int or a String at each leaf. A traversal of this tree would naturally be a [Either Int String].

Upvotes: 4

Claudiu
Claudiu

Reputation: 229581

Lists in Haskell can only have one type. If you want a list to handle multiple types, you'll need to create a new wrapper type which can represent both of the types you want to put into it, along with functions to extract the original type and handle it. For example, you could use Either.

Upvotes: 2

Related Questions