Aslan986
Aslan986

Reputation: 10314

How to define a nested lists

Trying to solve the Exercise 7 at this page I want to define the data type to write some value like:

(List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5]])

Nested list, any length, any depth.

I tried with this code:

data List a = Elem a | List [List a]

but it doesn't compile:

Parse error: naked expression at top level

How can it be done?

Upvotes: 2

Views: 2057

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 152682

Instead of a file containing this:

data List a = Elem a | List [List a]
(List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5]])

Try a file containing this:

data List a = Elem a | List [List a]
sampleListValue = List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5]]

By the way, a very similar type is also available in the standard libraries (I know you don't want to use this as it's a learning exercise, but keep in mind that it's available).

Upvotes: 8

Related Questions