【发布时间】:2018-10-20 12:28:09
【问题描述】:
我希望我的 Haskell 程序中有一些更高级别的函数调用其他函数,这些函数最终调用使用某些状态或配置的函数,而不必在所有这些函数调用中传递状态。我知道这是 state monad(或者可能是 Reader monad?)的经典用法。
(我也不确定是否应该使用 StateT(如下面的示例)来启用 IO,或者是否应该以某种方式单独输出结果。)
在这个阶段,我对这里的所有教程、博客文章和类似问题感到很困惑,无法找出解决方案。还是我误解了隐藏的东西?
这是一个小例子:
import Control.Monad.State
-- Here's a simple configuration type:
data Config = MkConfig {
name :: String
, num :: Int
} deriving Show
-- Here's a couple of configurations.
-- (They're hard coded and pre-defined.)
c1 = MkConfig "low" 7
c2 = MkConfig "high" 10
-- Here's a lower level function that explicitly uses the config.
-- (The String is ignored here for simplicity, but it could be used.)
fun :: Config -> Int -> Int
fun (MkConfig _ i) j = i*j
-- testA and GoA work fine as expected.
-- fun uses the different configs c1,c2 in the right way.
testA = do
a <- get
lift (print (fun a 2))
put c2
a <- get
lift (print (fun a 4))
goA = evalStateT testA c1
-- (c1 could be put at the start of testA instead.)
-- But what I really want is to use fun2 that calls fun,
-- and not explicitly need state.
-- But this function definition does not compile:
fun2 :: Int -> Int
fun2 j = 3 * fun cf j
-- fun needs a config arg cf, but where from?
-- I would like a similar way of using fun2 as in testB and goB here.
testB = do
a <- get
lift (print (fun2 3)) -- but fun2 doesn't take the state in a
put c2
a <- get
lift (print (fun2 42)) -- but fun2 doesn't take the state in a
goB = evalStateT testB c1
我想在我的程序中将配置隐藏在诸如 fun2 之类的高级函数之外,同时仍保留更改配置并使用新配置运行这些函数的能力。这是一个“如何做的问题”(除非我的想法完全错误)。
【问题讨论】:
标签: haskell state-monad