[Haskell-beginners] How to solve this using State Monad?

Henry Lockyer henry.lockyer at ntlworld.com
Thu May 31 02:24:08 CEST 2012


hi kak

On 30 May 2012, at 20:17, kak dod wrote:

> . . . can you please remove the IO stuff from your first (non-state monadic) example and repost the same example again?

Sure.   Here it is, with an essentially similar recursive design in the new non-IO, non-State-monad option. 
See if it makes any more sense..
br/ Henry

--
-- Version 3 - containg two alternative "String -> String" solutions:
-- 1) "ahaVanilla"    does not use the State monad
-- 2) "ahaStMonad" (was 'mystatemachine'in version 2)
-- 
-- the substring "YYY*" followed by spaces (0+) will be found
-- in the response string at the position corresponding to the first
-- occurrence of substring "aha!" in the input string
--

import Control.Monad.State

type MyState = Char

initstate, exitstate :: MyState
initstate = 'a'
exitstate = 'z'


ahaVanilla :: String -> String
ahaVanilla str = vanilla initstate str
  where vanilla _     []     = []
        vanilla state (c:cs) = let (responsechar, nextstate) = stateMC c state
                                in responsechar:( vanilla nextstate cs )


ahaStMonad :: String -> String
ahaStMonad str = evalState ( mapM charfunc str ) initstate
  where charfunc :: Char -> State MyState Char
        charfunc c = state (stateMC c)  


stateMC :: Char -> MyState -> (Char, MyState)
stateMC 'a' 'a' = ('Y', 'b')
stateMC 'h' 'b' = ('Y', 'c')
stateMC 'a' 'c' = ('Y', 'd')
stateMC '!' 'd' = ('*', 'z')
stateMC  _  'z' = (' ', 'z')
stateMC  _   _  = ('N', 'a')




More information about the Beginners mailing list