这甚至可能吗?我有一个main将用户给出的Int(宽度)保存为变量,但是我需要在一堆其他函数中使用该变量...除了将'width'作为参数添加之外,还有其他方法吗?每个功能?
答案 0 :(得分:3)
我将展示一个读者monad使用的简单示例。
此代码:
area :: Double -> Double -> Double
area height width = height * width
main = do
width <- fmap read getLine
let result = area 42 width
print result
变为:
import Control.Monad.Reader
area :: MonadReader Double m => Double -> m Double
area height = do
width <- ask
return (width * height)
main :: IO ()
main = do
width <- fmap read getLine
let result = runReader (area 42) width
print result
这看起来更复杂,但是当你有很多&#34;配置&#34;它实际上相当不错。传递的参数。
import Control.Monad.Reader
data Config = Config { width :: Double, color :: String, etc :: String }
area :: MonadReader Config m => Double -> m Double
area height = do
w <- asks width
return (w * height)
main :: IO ()
main = do
w <- fmap read getLine
c <- undefined -- todo get color param
e <- undefined -- todo get etc param
let result = runReader (area 42) (Config w c e)
print result