Search code examples
haskellshowuser-defined-types

How to show a user-defined data type in Haskell


So I'm trying to define my own data type which expresses natural numbers recursively, as such:

 data Nat = Zero | Succ Nat

This function works correctly:

 showNat :: Nat -> String
 showNat Zero = "Zero"
 showNat (Succ k) = "Succ " ++ (showNat k)

However, I don't want to have to call it every time I want to output a Nat to the screen. I attempted this:

  instance Show Nat where
  show Zero = "Zero"
  show (Succ k) = "Succ " ++ Main.show k

But it returns an error:

• No explicit implementation for
    either ‘showsPrec’ or ‘Prelude.show’
• In the instance declaration for ‘Show Nat’
|
| > instance Show Nat where   |            ^^^^^^^^

How can I correctly write instances of 'Show'?


Solution

  • The instantiation seems over-complicated. This is enough:

    data Nat = Zero | Succ Nat
    
    showNat :: Nat -> String
    showNat Zero = "Zero"
    showNat (Succ k) = "Succ " ++ (showNat k)
    
    instance Show Nat where
        show = showNat
    

    Alternatively, one might like to use the automatically generated show using deriving:

    data Nat = Zero | Succ Nat deriving (Show)
    

    In this case, nats will be shown as Succ (Succ Zero), not as Succ Succ Zero as intended in the original code.