Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"instance Show State where" doesn't compile

This is the State Monad code I am trying to figure out

data State a = State (Int -> (a, Int)) 
instance Monad State where
    return x = State (\c -> (x, c))     
    State m >>= f = State (\c ->
        case m c of { (a, acount) ->
            case f a of State b -> b acount})

getState = State (\c -> (c, c))
putState count = State (\_ -> ((), count))

instance Show State where  -- doesn't work
    show (State a) = show a   -- doesn't work

I am trying to make State as instance of Show so that I can see the action of getState and putState count on the ghci prompt.

Any tutorial or link to State Monad material would be nice too.

like image 263
nobody Avatar asked Jun 16 '26 14:06

nobody


2 Answers

Here's is a Show instance that can help see what's going on:

instance Show a => Show (State a) where
  show (State f) = show [show i ++ " => " ++ show (f i) | i <- [0..3]]

Then you can do:

*Main> getState
["0 => (0,0)","1 => (1,1)","2 => (2,2)","3 => (3,3)"]
*Main> putState 1
["0 => ((),1)","1 => ((),1)","2 => ((),1)","3 => ((),1)"]
like image 174
Sjoerd Visscher Avatar answered Jun 18 '26 05:06

Sjoerd Visscher


In Haskell, typeclasses classify only types of the same kind. Monad classifies types of kind * -> *, while Show classifies types of kind *. Your State type has kind * -> * which is why there isn't a problem with your Monad instance, but there is a problem with your Show instance. State is called a "type constructor" because it consumes a type in order to produce another type. Think of it sort of like function application at the type level. You can therefore apply a specific type and make instances of that:

instance Show (State Char) where
    show _ = "<< Some State >>"

Now, this isn't a very useful instance, try something like Sjoerd's suggestion to get a more meaningful Show instance. Notice that his version uses a generic type with a constraint.

instance (Show a) => Show (State a) where
    -- blah blah

The generic type is a, and the constraint is (Show a) =>, in other words, a itself must be an instance of Show.

like image 24
Dan Burton Avatar answered Jun 18 '26 03:06

Dan Burton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!