gpt4 book ai didi

haskell - Reader Monad - 琐碎案例的解释

转载 作者:行者123 更新时间:2023-12-05 08:41:29 24 4
gpt4 key购买 nike

我一直在努力掌握 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com