gpt4 book ai didi

haskell - 有没有办法在 Haskell 中记住一个值?

转载 作者:行者123 更新时间:2023-12-04 13:28:49 26 4
gpt4 key购买 nike

我在 Haskell 中有以下功能:

memdb = -- load the contents of a database into memory as a Map

然后我有以下行:
map (\x -> memdb ! x) values

我希望 memdb 只生成一次 map ,而不是在 map 的每次迭代中生成一次。 .我可以使用这样的东西来做到这一点:
make_memdb = -- equivalent to memdb in previous example
memdb <- make_memdb
map (\x -> memdb ! x) values

但这意味着我必须通过 memdb在每个使用它的功能中。有什么办法可以:

一个。避免重新计算 memdb每次它被称为 OR

湾。保存 make_memdb 中产生的值作为一个常数,这样我就可以避免将它传递给使用它的每个函数?

最佳答案

由于您的 map 来自数据库,这意味着它不能是常数,因为它在您的应用程序运行之间可能会有所不同。

But this would mean that I would have to pass memdb in to every function that uses it.



是的,但是有一些工具可以让这件事变得不像听起来那么糟糕。特别是,这听起来像是 the reader monad 的完美用例。 !

Reader monad 通常在你有一些值(value)时使用,比如配置,你想在程序开始时加载它,然后能够在你的程序中访问它,而不必一直显式地传递它。这是一个简短的示例,说明您将如何使用它:
main = do
memdb <- make_memdb -- Get the memdb from the database once and for all
runReaderT foo memdb

foo = do
memdb <- ask -- Grab the memdb. Will not reload from the database
liftIO $ putStrLn "Hello, world" -- IO actions have to be lifted
-- [...]

也可以看看:
  • Real World Haskell: The reader monad
  • Learn You a Haskell: Reader? Ugh, not this joke again
  • 关于haskell - 有没有办法在 Haskell 中记住一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7210510/

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