2013年1月15日火曜日

Haskell State Without Monad

Inspired by an articl
Monad for the Working Haskell Programmer -- a short tutorial Theodor Norvell
I tried to make it more clear and coded the following.

And the result is

*Main> (cutDummy >=> downgradeIfEven) Six
(Five,"Downgraded")

*Main> (cutDummy >=> downgradeIfEven) Dummy
(Two,"Upgraded")

data State = Dummy | One | Two | Three | Four | Five | Six
                deriving (Show,Eq,Enum,Ord,Read)

type GroupStateAndFlag = State->(State, Int)
cutDummy::GroupStateAndFlag
cutDummy s 
            | s == Dummy = (One, fromEnum $ succ s)
            | otherwise = (s, fromEnum s)

type ChangeGradeAndInfo = State->(State,String)
downgradeAndInfo,upgradeAndInfo::ChangeGradeAndInfo
downgradeAndInfo s 
            | s== One = (Six, "Downgraded and Reversed")
            | otherwise = (pred s, "Downgraded") 

upgradeAndInfo s 
            | s== Six = (One, "Upgraded and Reversed")
            | otherwise = (succ s, "Upgraded") 

downgradeIfEven::Int->ChangeGradeAndInfo
downgradeIfEven a
                | even a =  downgradeAndInfo
                | otherwise = upgradeAndInfo


(>=>)::GroupStateAndFlag->(Int->ChangeGradeAndInfo)->ChangeGradeAndInfo
stateManupilator1 >=> evaluator = 
                \ state1 -> let     
                                (state2, result) = stateManupilator1 state1      
                                -- Manupilate the State, pack it with a result 
                                stateManupilator2 = evaluator result             
                                -- Pass the result to a evaluator, 
                                -- pass it to another state manupilator
                             in stateManupilator2 state2

ret::a->State->(State,a)
ret result = \state -> (state, result)

0 件のコメント:

コメントを投稿