0

I am wondering whether my definition of a list is less capable than the regular implementation. I am having problems creating a list of lists with the below definition:

data List a =
  Nil
  | Cons a (List a)
  deriving (Eq, Ord, Show)

I do not see how to create a list like [[2],[3]] with my definition of list.

The simplest instance of a nested list is just [[]] which I think I can recreate with Cons Nil Nil. The second simplest instance of a nested list is [[1]]. This is Cons (Cons 1 Nil) Nil afaics.

However, like I said do not see how to create the list [[2],[3]] with my definition above. How do I do it? (It should be possible, since an exercise asks me to create a monad instance for the list definition above).

1 Answer 1

3

Let's first consider, how would you express [x,y]?

Cons x (Cons y Nil)

Now put in x = [2]:

Cons (Cons 2 Nil) (Cons y Nil)

and y = [3]:

Cons (Cons 2 Nil) (Cons (Cons 3 Nil) Nil)
Sign up to request clarification or add additional context in comments.

1 Comment

I am amazed that I was able to understand how to make the monad instance but not see this. Must have forgotten a Nil somewhere and had the REPL choke. Oh, well.

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.