Sushodhan
Sushodhan

Reputation: 410

Generic Stack implementation in haskell

I am trying to create a generic implementations of stack operations. On compiling it gives an error:

Duplicate instance declarations:
      instance Show a => Show (Stack a) -- Defined at stackOp.hs:2:29
      instance Show a => Show (Stack a) -- Defined at stackOp.hs:11:10

Here is my code:

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

printelems :: (Show a) => [a] -> String
printelems [] = ""
printelems x = show x
printelems (x:xs) = show x ++ "->" ++ (printelems xs)



instance (Show a) => Show (Stack a)
 where
 show (Stack l) = printelems l

empty :: Stack a
empty = []

push :: a -> Stack a -> Stack a
push x s = x:s

Upvotes: 0

Views: 754

Answers (1)

Stéphane Laurent
Stéphane Laurent

Reputation: 84519

Here is your code with three corrections:

-- do not derive Show since you define it
data Stack a = Stack [a]
               deriving (Eq,Ord)

-- there was a redundant pattern matching here
printelems :: (Show a) => [a] -> String
printelems []     = ""
printelems (x:xs) = if null xs then show x else show x ++ "->" ++ printelems xs

instance (Show a) => Show (Stack a)
 where
 show (Stack l) = printelems l

-- "Stack" was missing
empty :: Stack a
empty = Stack []

-- "Stack" was missing
push :: a -> Stack a -> Stack a
push x (Stack s) = Stack (x:s)

Upvotes: 1

Related Questions