Sep 28, 2010

More on monad haskell

Monad transformers
Monads transformers are also in a formata of monads. So we must make MaybeT m an instance of the Monad class.
instance Monad m => Monad (MaybeT m) where
return = MaybeT . return . Just

This will get the monads return and send it ot the monadts constructore. This thing can be wriiten as,
x >>=f= MaybeT $ do maybe_value <- runMaybeT x case maybe_value of Nothing -> return Nothing
Just value -> runMaybeT $ f value

List transformer
newtype ListT m a = ListT { runListT :: m [a] }

We can transform list also and to do that we need to crerate a datatype with a constructoore which takes an argument.

This is a library which can transfer the non-monadic functions to monadic ones. The function is like this.
liftM :: Monad m => (a1 -> r) -> m a1 -> m r

Converting non-monadic:- myFn $ NonMonadic
Converting monadic :- myFn `liftM` monadic

Pasing monad
This is more powerful parser with monads like Maybe, list and sate. This will use parcer librery functions also. So first of all we must import relevent librery functions to our program.
import System
import Text.ParserCombinators.Parsec hiding (spaces)
Now we are going to use a parser librery function call oneOf
symbol :: Parser Char
symbol = oneOf "!$%&|*+-/:<=>?@^_~"

This will keep track of each charactor. Then we must make some arrangements to handle the errors too.
readExpr :: String -> String
readExpr input = case parse symbol "lisp" input of
Left err -> "No match: " ++ show err
Right val -> "Found value"

Now we can write the program.
main :: IO ()
main = do args <- getArgs
putStrLn (readExpr (args !! 0))

Now you can run this by doing
ghc -package parsec -o filename.hs

No comments:

Post a Comment

Your comments are always welcome ...