1

I am trying to play with MonadState monad and especially with 'modify' function.

When I try

f :: (MonadState s m, Num s) => m ()
f = put 1

It works without any problems, but when I try to set State as String, Char or List I get this error:

• Non type-variable argument in the constraint: MonadState Char m
  (Use FlexibleContexts to permit this)
• When checking the inferred type
    a :: forall (m :: * -> *). MonadState Char m => m ()

The same happens for:

b = modify (1:)

• Non type-variable argument in the constraint: MonadState [a] m
  (Use FlexibleContexts to permit this)
• When checking the inferred type
    b :: forall a (m :: * -> *). (MonadState [a] m, Num a) => m ()

Thank you for your help.

lukas kiss
  • 381
  • 2
  • 15
  • 4
    do what it tells you - enable `FlexibleContexts` (in your file with `{-# LANGUAGE FlexibleContexts #-}` in GHCi with `:set -XFlexibleContexts`) - that's a pretty safe/common extension and it should fix your problem here – Random Dev May 19 '21 at 19:35

1 Answers1

4

As the error indicates, you need to enable the FlexibleContexts extension in Haskell to run this. You can do this by adding a language pragma at the top of your file:

{-# LANGUAGE FlexibleContexts #-}

b = modify (1:)

or if you work with ghci you enable this extension with the -XFlexibleContexts flag:

$ ghci -XFlexibleContexts
GHCi, version 8.6.5: http://www.haskell.org/ghc/  :? for help
Prelude> import Control.Monad.State.Class
Prelude Control.Monad.State.Class> b = modify (1:)
Prelude Control.Monad.State.Class> 
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • 2
    For the reasons why this is required see: https://stackoverflow.com/a/31253041/163177 and https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/flexible_contexts.html – John F. Miller May 19 '21 at 20:31