JavascriptLoser
JavascriptLoser

Reputation: 1962

Define a data type to represent a nested list of strings

I am just starting out learning haskell and I find myself challenged trying to define a data type to represented a list of lists of String's. That sounds a little confusing but this is essentially what a data type of this form would look like:

[["abc", "def", "ghi"], ["abc", "def", "ghi"], ["abc", "def", "ghi"]]

Each of the inner lists will always have a length of 3, but the strings inside can be of arbitrary length greater than one.

I tried this:

data MyType = Lists [String] | List [MyType]

But I'm not sure if its correct, or maybe that I don't know how to use it. If it is correct, how would I go about constructing a list of lists of these words, or if it is incorrect, what would be the correct way of defining this type?

Upvotes: 0

Views: 768

Answers (3)

Euge
Euge

Reputation: 749

If you just want a type of lists whose elements are "three element lists", then you can just use a list of triples (tuples of three elements).

type MyType = [(String, String, String)]

For example, [], [("a","b","c")] or [("abc", "def", "ghi"), ("abc", "def", "ghi"), ("abc", "def", "ghi")] are inhabitants of MyType.

Comment aside: As other anwers stated, if the lenght of the lists is fixed, then it's not a list what you are talking about, it's rather a vector or tuple.

Upvotes: 0

Netwave
Netwave

Reputation: 42698

You only need to define the type, data is used for other purpouses:

type MyType = [(String, String, String)]

Check this answer If you really want to create a new Algebraic data type, for example:

data MyType = Tup3 String String String | List [MyType] deriving Show

Live example

Upvotes: 2

Igor Drozdov
Igor Drozdov

Reputation: 15045

the inner lists will always have a length of 3

The data structure you're looking for is tuple. Its fundamental difference from list is that tuple's type depends on the number of elements in it. You can read about it here

It's going to look like:

[("abc", "def", "ghi"), ("abc", "def", "ghi"), ("abc", "def", "ghi")]

The type of this structure is [(String, String, String)]

Therefore, MyType will be something like:

data MyType = Lists (String, String, String) | List [MyType]

Upvotes: 1

Related Questions