注意:这是一个练习,我试图了解事情是如何运作的。
我试图让在 Haskell 中做这样的事情成为可能:
f :: Integer -> Integer
f n = def $ do
i <- var n
while i (>0) $ do
i -= lit 1
return i
-- for now, my program returns n
下面是我的程序。在这一点上,我不明白为什么它不起作用,但由于某种原因,变量没有改变。
import Control.Monad.State
data Lit a = Lit a
type Variable a = State Integer a
def :: Variable (Lit a) -> a
def (State f) = fromLit . fst . f $ 0
fromLit :: Lit a -> a
fromLit (Lit a) = a
lit :: a -> Lit a
lit l = Lit l
var :: a -> Variable (Lit a)
var v = State $ \x -> (lit v, x)
while :: Lit a -> (a -> Bool) -> Variable () -> Variable ()
while (Lit r) cond act = do
if cond r then do
_ <- act
while (Lit r) cond act
-- or act >> while (Lit r) cond act
else return ()
op :: (Integer -> Integer -> Integer) -> Lit Integer -> Lit Integer -> Variable ()
op f (Lit a) (Lit b) = State $ \n -> ((), if n == a then f a b else n)
-- that is, if the state is (a) change it to (f a b), else don't change it
(+=) = op (+)
(-=) = op (-)
(*=) = op (*)
请帮助我了解这里出了什么问题以及如何改进代码。谢谢你。