gpt4 book ai didi

haskell - 什么是 "a function that you call"和什么是 "a function that call you"?

转载 作者:行者123 更新时间:2023-12-02 02:57:48 26 4
gpt4 key购买 nike

我试图了解 Haskell Reader monad 是什么,但我在书中的这一部分遇到了困难:

The “read-only” nature of the type argument r means that you can swap in a different type or value of r for functions that you call, but not for functions that call you. The best way to demonstrate this is with the withReaderT function which lets us start a new Reader context with a different argument being provided:

withReaderT 
:: (r' -> r)
-- ^ The function to modify the environment.
-> ReaderT r m a
-- ^ Computation to run in the modified environment.
-> ReaderT r' m a

那么,首先,请您指定什么是“您调用的函数”以及什么是“调用您的函数”?

最佳答案

我认为这只是对英语的误解。当它说“你”时,它只是意味着“你当前关心的代码”。

如果你正在编写一个函数myfunction:

myfunction x y = sqrt (x*x + y*y)
main = print $ myfunction 3 4

如果说你是myfunction,那么sqrt就是你调用的函数,main就是调用你的函数。

本书试图说明的一点是,您的代码可以在您想要的任何环境中调用函数,但这些函数不能更改代码的环境。反过来,调用您的代码的代码可以指定它希望您看到的任何环境,但您不能更改该代码的环境。

这是一个注释示例:

import Control.Monad.IO.Class
import Control.Monad.Trans.Reader
import Control.Monad.Trans

showValue :: String -> ReaderT String IO ()
showValue str = do
s <- ask
lift . putStrLn $ str ++ ": " ++ s

-- This is me (i.e. my code).
-- I show the environment twice, and it's guaranteed to be the same both times
myFunction :: ReaderT String IO ()
myFunction = do
showValue "myFunction sees"
withReaderT (const "Something Completely Different") functionThatICall
showValue "myFunction still sees"

-- This is a function that I call.
-- I decide what value it sees, but it can't decide what I see.
functionThatICall :: ReaderT String IO ()
functionThatICall = showValue "functionThatICall sees"

-- This is a function that calls me. It decides what value I see,
-- but I can't change what it sees.
functionThatCallsMe :: ReaderT String IO ()
functionThatCallsMe = do
showValue "functionThatCallsMe sees"
myFunction
showValue "functionThatCallsMe still sees"


main = runReaderT functionThatCallsMe "Hello World"

关于haskell - 什么是 "a function that you call"和什么是 "a function that call you"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62479691/

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