2

complete noob to Haskell here with probably an even noobier question. I'm trying to get ghci output working and am stuck on instance declarations. How could I declare an instance for "(Show (Stack -> Stack))" given:

data Cmd = LD Int
         | ADD
         | MULT
         | DUP
         deriving Show

type Prog = [Cmd]

type Stack = [Int]

type D = Stack -> Stack

I've been trying to create a declaration like:

instance Show D where show = Stack

but all my attempts have resulted in illegal instance declarations. Any help and/or references much appreciated!

2
  • 1
    It is not clear from your code what you would want e.g. show (\s -> 1:s) to return. Commented Apr 21, 2010 at 21:43
  • 1
    I have a hunch you are trying to define an instance of Show for D not because it is really what you want (it's hard to imagine what it could do) but because the compiler is telling you that you need one because you have a type error somewhere; is that possible? If so, the solution is to fix your other code. Commented Apr 23, 2010 at 7:25

1 Answer 1

7

First of all, by default, type synonyms (that is, stuff defined using type) aren't legal in instance declarations. There's a GHC extensions to allow this, however.

Beyond that, in this specific case, show needs to return a String; your instance is trying to return a... type synonym name, which doesn't even make sense to begin with, and besides refers to a list of Int, which is the wrong return type for show.

Finally, D is a function type--what is that supposed to show, anyway? There's really not much you can meaningfully do with a Show instance on a function type, in most cases.

If you just want it to say "this is type D", you could write an instance like this:

{-# LANGUAGE TypeSynonymInstances #-}
instance Show D where show _ = "Stack -> Stack"

I'm not sure how useful that is in practice, though.

Sign up to request clarification or add additional context in comments.

1 Comment

Maybe he wants to show the mutation from one [ Int ] to another [ Int ]? Not certain how you would go intercepting this, displaying the parameter then the resultant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.