首页 > 解决方案 > 为州实施表演

问题描述

好吧,这个话题之前已经讨论过,所以我链接到它。

上一个stackoverflow问题

所以我确信它当时有效,但时间已经改变了:)

作为一个 Haskell 新手,迈出一小步,这会让我更进一步。我已经尝试了各种解决方案来解决各种问题。

建议的解决方案

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

编译器报告。

 myfuncs.hs:31:11: error:
     Not in scope: data constructor ‘State’
     Perhaps you meant one of these:
       ‘StateT’ (imported from Control.Monad.State),
       variable ‘state’ (imported from Control.Monad.State)
    |
 31 |     show (State f) = show [show i ++ " => " ++ show (f i) | i <- [0..3]]
    |

我将不胜感激 State state 和 StateT 也理解如何解释 :info State 。

type State s = StateT s Data.Functor.Identity.Identity :: * -> *
       -- Defined in ‘Control.Monad.Trans.State.Lazy’

同样的问题也适用于信息:状态

class Monad m => MonadState s (m :: * -> *) | m -> s where
 ...
 state :: (s -> (a, s)) -> m a
       -- Defined in ‘Control.Monad.State.Class’

不确定我会理解答案,但是感谢所有帮助。

标签: haskellfunctional-programming

解决方案


我构建了Universe包,目的是在小域(除其他外)上显示功能。您可以使用它来为此创建Show实例State

{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE UndecidableInstances #-}

import Control.Monad.State
import Data.Universe
import Data.Universe.Instances.Reverse

deriving instance (Finite s, Show s, Show (m (a,s))) => Show (StateT s m a)

试试看:

> modify not :: State Bool ()
StateT {runStateT = [(False,Identity ((),True)),(True,Identity ((),False))]}

在包中包含类似这样的内容(以及类似的ReaderT等)可能会很有趣universe-reverse-instances。我将不得不考虑一个理智的方法来做到这一点。

从头开始解释可能是一个比 SO 答案更适合的任务,但是对于这种类型,网上有很多教程StateStateT


推荐阅读