Making Haskell Instance Declarations

fill in the noob for Haskell here, maybe even with a noobier question. I am trying to get ghci working and getting stuck in the instance declarations. How can I declare an instance for "(Show (Stack -> Stack)" specified:

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

type Prog = [Cmd]

type Stack = [Int]

type D = Stack -> Stack

      

I am trying to create an ad like:

instance Show D where show = Stack

      

but all my attempts led to the announcement of illegal copies. Any help and / or links are greatly appreciated!

+2


a source to share


1 answer


First of all, by default, type synonyms (that is, data defined with type

) are not legal in instance declarations. However, the GHC extensions allow you to do this.

Also, in this particular case, show

you need to return a String

; your instance is trying to return a type synonym name ... which doesn't even make sense to begin with, and furthermore is referencing a list Int

, which is the wrong return type for show

.

Finally D

- this is the type of function - what does it mean for show

, anyway? Indeed, in most cases, you can hardly do anything meaningful with an instance show

for a function type.



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

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

      

I'm not sure how useful this is in practice.

+6


a source







All Articles