subprimeloads
subprimeloads

Reputation: 392

Reversing a Custom Data Type

Consider the following data type for a length ordered list:

data LordL a = LordL Int [a] deriving (Show, Eq, Ord)

Here is a simple constructor:

LordL :: [a] -> LordL a
LordL xs = LordL (length xs) xs

ex) LordL [1,2,3] => LordL 3 [1,2,3]

Now i've been trying to implement a method which would consist of reversing the list but have not been able to get it working. Here is what i'v come up with:

rev xs = LordL (length xs) (reverse xs)

When I try and run the file this is the message i'm getting:

Couldn't match expected type ‘[a]’ with actual type ‘LordL a’

Is there something I should be doing differently?

Upvotes: 1

Views: 100

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

Here rev likely should take a LordL a object, so you can "unpack" the Lordl object, and reverse the list, so:

rev :: LordL a -> LordL a
rev (LordL l xs) = LordL l (reverse xs)

We do not have to recalculate the length, since the length of the reverse of a list is the same as the length of that list.

Upvotes: 3

Related Questions