Michael Tran
Michael Tran

Reputation: 31

How to access elements of a custom List data type?

I created a custom List type and I'm trying to implement the zip function for it. But I cant figure it out, it always throw an error on the last line.

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

listZip :: List a -> List a -> List a
listZip _ Empty = Empty
listZip Empty _ = Empty
listZip (Cons x1 (x2)) (Cons y1 (y2)) = Cons (Cons x1 y1) (listZip x2 y2)

Upvotes: 1

Views: 40

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

The return type looks wrong, you probably want to return a list of 2-tuples, so:

listZip :: List a -> List a -> List (a, a)

or more generic:

listZip :: List a -> List b -> List (a, b)

Then you implement this with:

listZip :: List a -> List b -> List (a, b)
listZip _ Empty = Empty
listZip Empty _ = Empty
listZip (Cons x1 (x2)) (Cons y1 (y2)) = Cons … (listZip x2 y2)

where I leave the part as an exercise.

Upvotes: 4

Related Questions