作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我一直在努力掌握 reader monad 并遇到了 this tutorial .在其中,作者提出了这个例子:
example2 :: String -> String
example2 context = runReader (greet "James" >>= end) context
where
greet :: String -> Reader String String
greet name = do
greeting <- ask
return $ greeting ++ ", " ++ name
end :: String -> Reader String String
end input = do
isHello <- asks (== "Hello")
return $ input ++ if isHello then "!" else "."
我知道这是一个展示机制的简单示例,但我想弄清楚为什么它会比做类似的事情更好:
example3 :: String -> String
example3 = end <*> (greet "James")
where
greet name input = input ++ ", " ++ name
end input = if input == "Hello" then (++ "!") else (++ ".")
最佳答案
Reader
在实际代码中并不经常单独使用。正如您所观察到的,它并不比向您的函数传递一个额外的参数更好。但是,作为 monad 转换器的一部分,它是通过应用程序传递配置参数的绝佳方式。通常这是通过向需要访问配置的任何函数添加 MonadReader
约束来完成的。
下面是一个更真实的例子的尝试:
data Config = Config
{ databaseConnection :: Connection
, ... other configuration stuff
}
getUser :: (MonadReader Config m, MonadIO m) => UserKey -> m User
getUser x = do
db <- asks databaseConnection
.... fetch user from database using the connection
然后你的 main
看起来像这样:
main :: IO ()
main = do
config <- .... create the configuration
user <- runReaderT (getUser (UserKey 42)) config
print user
关于haskell - Reader Monad - 琐碎案例的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49495838/
我认为这相对简单,但我很困惑,因为我是类图的新手。 我将要创建一个程序(用 Java)来管理麦当劳的员工类型。因此,考虑为对象建模。 为了简单起见,麦当劳只有两种员工,“主管”和“船员”,两者都是按月
我有一个很小的 Android 项目,是我拼凑而成的,用于了解 Android 单元和仪器测试。我使用dog.ceo API 来获取狗的随机图像。程序本身按其应有的方式运行。但是,每当我运行或调试
我是一名优秀的程序员,十分优秀!