Parsec 不允许您直接开箱即用地执行此操作,但您可以使用 Parsec 的公共 API 实现此目的,如下所示:
{-# LANGUAGE ScopedTypeVariables #-}
import Text.Parsec
changeState
:: forall m s u v a . (Functor m, Monad m)
=> (u -> v)
-> (v -> u)
-> ParsecT s u m a
-> ParsecT s v m a
changeState forward backward = mkPT . transform . runParsecT
where
mapState :: forall u v . (u -> v) -> State s u -> State s v
mapState f st = st { stateUser = f (stateUser st) }
mapReply :: forall u v . (u -> v) -> Reply s u a -> Reply s v a
mapReply f (Ok a st err) = Ok a (mapState f st) err
mapReply _ (Error e) = Error e
fmap3 = fmap . fmap . fmap
transform
:: (State s u -> m (Consumed (m (Reply s u a))))
-> (State s v -> m (Consumed (m (Reply s v a))))
transform p st = fmap3 (mapReply forward) (p (mapState backward st))
请注意,它需要 和 之间的正向和反向u
转换v
。原因是首先您需要将环境状态转换为本地状态,运行内部解析器,然后再转换回来。
ScopedTypeVariables
和本地类型签名只是为了清楚起见——如果你愿意,可以随意删除它们。