Haskell mapm_不打印
因此,我编写了一个程序来查询外汇API(外汇),它的工作方式就像魅力一样,但是当我想查询每个可用的货币对时,它会评估所有API调用,因为要执行时间很长,但没有打印什么。
import Data.Functor ((<&>))
supportedPairs :: IO (Maybe [(String, String)])
forex :: String -> String -> IO (Maybe (Scientific, UnixTime))
main :: IO ()
main = do
x <- supportedPairs
mapM_ (flip (<&>) print . uncurry forex) (fromJust x)
-- this prints nothing at all
单个调用正常工作:
main = do
x <- supportedPairs
u <- (uncurry forex . (flip (!!) 10 . fromJust)) x
print u
-- this prints "Just (438.685041,UnixTime {utSeconds = 1649588583, utMicroSeconds = 0})"
为什么对结果进行了评估,为什么mapm _
不打印结果?如果我正确理解Haskell的懒惰,那么如果不打印结果,则不应首先对其进行评估?
So I wrote a program to query a forex API (foreign exchange), and it works like a charm, but when I want to query every currency pair available, it evaluates all API calls as it takes a long time to execute but prints nothing.
import Data.Functor ((<&>))
supportedPairs :: IO (Maybe [(String, String)])
forex :: String -> String -> IO (Maybe (Scientific, UnixTime))
main :: IO ()
main = do
x <- supportedPairs
mapM_ (flip (<&>) print . uncurry forex) (fromJust x)
-- this prints nothing at all
The single calls work just fine like this:
main = do
x <- supportedPairs
u <- (uncurry forex . (flip (!!) 10 . fromJust)) x
print u
-- this prints "Just (438.685041,UnixTime {utSeconds = 1649588583, utMicroSeconds = 0})"
Why doesn't the mapM_
print the results although they are evaluated? If I understood Haskell's laziness correctly, then if the results are not to be printed they should not be evaluated in the first place?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
检查类型:
print
是... -> IO()。
因此,
... <&> print
是IO (IO ())
。注意这里的双IO。因此,对其进行映射将运行“最外部 IO”,但不会运行“最内部 IO”。更具体地说,比较一下:
这里只执行第一个
print True
:第二个 IO 操作用于定义y
但直到我们运行y
它不会被执行。最后一点:在这里,您不需要
<&>
因为这会创建嵌套 IO。使用flip (>>=) print
(或(=<<) print
,或(>>= print)
>) 而不是flip <&>打印
。Check the types:
print
is... -> IO ()
.Therefore,
... <&> print
isIO (IO ())
. Note the double IO here.Hence, mapping over that, will run the "outermost IO" but not the "innermost IO". More concretely, compare this:
Only the first
print True
here is executed: the second IO action is used to definey
but until we runy
it won't be executed.The final point: here, you do not need
<&>
since that creates the nested IO's. Useflip (>>=) print
(or(=<<) print
, or(>>= print)
) instead offlip <&> print
.