【发布时间】:2014-11-08 23:45:10
【问题描述】:
TL:DR: 有没有办法在不传递参数的情况下执行示例 3
我正在尝试了解 haskell (Control.Monad.State) 中的状态单子。我做了一个极其简单的函数:
示例 1
example :: State Int Int
example = do
e <- get
put (e*5)
return e
这个例子适用于 ghci...
runState example 3
(3,15)
我对其进行了修改,使其能够接受参数......
示例 2
example :: Int -> State Int Int
example n = do
e <- get
put (e*n)
return e
也适用于 ghci...
runState (example 5) 3
(3,15)
我让它递归,计算满足某些条件的计算所需的步数
示例 3
example :: Int -> State Int Int
example n = do
e <- get
if (n /= 1)
then do
put (succ e)
example (next n)
else return (succ e)
next :: Int -> Int
next n
| even n = div n 2
| otherwise = 3*n+1
ghci
evalState (example 13) 0
10
我的问题是,有没有办法在不显式传递值的情况下执行前面的示例?
【问题讨论】:
标签: haskell recursion monads state-monad