03/07/21 20:22
>>734
知らん。気になるのなら、たとえば、こうすればちゃんとモナドになる。
module Main where
instance (Num a) => Monad ((,) a) where
(>>=) (sub, main) f = (sub+sub', main') where
(sub', main') = f main
return main = (0, main)
>>733
まずちょっと修正...スマソ。
import Monad -- 追加
instance Monad ReadR where
ReadR r >>= fr = ReadR (\str -> [ret| (v,str') <- r str, ret <- fr v `runr` str'])
return v = ReadR (\str -> [(v, str)])
fail s = mzero -- 以下追加
instance MonadPlus ReadR where
mzero = ReadR (\s -> [])
mplus (ReadR f) (ReadR g) = ReadR (\s -> f s ++ g s)
用途としては、下のようなコード(やさしいHaskell 8.3節からコピペ)のtuvwxのような変数を書かなくてもよくすること。それだけです。
>readsTree :: (Read a) => ReadS (Tree a)
>readsTree s = [(Branch l r, x) | ("<", t) <- lex s,
> (l, u) <- readsTree t,
> ("|", v) <- lex u,
> (r, w) <- readsTree v,
> (">", x) <- lex w]
> ++
> [(Leaf x, t) | (x, t) <- reads s]