これに関する情報を見つけることができなかったことに驚いています。困っているのは私だけでしょう。
それで、ダッシュカウンターがあるとしましょう。文字列内のダッシュの数を数えて、文字列を返したいです。parsec の状態処理を使用すると機能しない例を挙げたふりをします。したがって、これは機能するはずです:
dashCounter = do
str <- many1 dash
count <- get
return (count,str)
dash = do
char '-'
modify (+1)
実際、これはコンパイルされます。さて、私はそれを使用しようとします:
:t parse dashCounter "" "----"
parse dashCounter "" "----"
:: (Control.Monad.State.Class.MonadState
t Data.Functor.Identity.Identity,
Num t) =>
Either ParseError (t, [Char])
わかりました、それは理にかなっています。状態と文字列を返す必要があります。涼しい。
>parse dashCounter "" "----"
<interactive>:1:7:
No instance for (Control.Monad.State.Class.MonadState
t0 Data.Functor.Identity.Identity)
arising from a use of `dashCounter'
Possible fix:
add an instance declaration for
(Control.Monad.State.Class.MonadState
t0 Data.Functor.Identity.Identity)
In the first argument of `parse', namely `dashCounter'
In the expression: parse dashCounter "" "----"
In an equation for `it': it = parse dashCounter "" "----"
おっとっと。しかし、そもそもどうして機能することを期待できたのでしょうか? 初期状態を入力する方法はありません。
関数もあります:
>runPT dashCounter (0::Int) "" "----"
しかし、同様のエラーが発生します。
<interactive>:1:7:
No instance for (Control.Monad.State.Class.MonadState Int m0)
arising from a use of `dashCounter'
Possible fix:
add an instance declaration for
(Control.Monad.State.Class.MonadState Int m0)
In the first argument of `runPT', namely `dashCounter'
In the expression: runPT dashCounter (0 :: Int) "" "----"
In an equation for `it':
it = runPT dashCounter (0 :: Int) "" "----"
その上でrunStateを実行する必要があるか、内部で既に実行している関数が必要なように感じますが、ここからどこに行くべきかわかりません。
編集:もっと明確に指定する必要がありました.parsecの状態処理を使用したくありませんでした. その理由は、バックトラックが、解決しようとしている問題で収集するものに影響を与えたくないという気持ちがあるからです。
ただし、McCann 氏はこれをどのように組み合わせるかを考え出しており、最終的なコードは次のようになります。
dashCounter = do
str <- many1 dash
count <- get
return (count,str)
dash = do
c <- char '-'
modify (+1)
return c
test = runState (runPT dashCounter () "" "----------") 0
どうもありがとう。