gpt4 book ai didi

haskell - 在 Haskell 中,性能和绑定(bind)

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

我刚刚学习 Haskell,并从教程网站编写了两个程序,这样

maximumnowhere :: (Ord a) => [a] -> a
maximumnowhere [] = error "empty"
maximumnowhere [x] = x
maximumnowhere (x:xs) = if x > maximumnowhere xs then x else maximumnowhere xs

maximumwhere :: (Ord a) => [a] -> a
maximumwhere [] = error "empty"
maximumwhere [x] = x
maximumwhere (x:xs) = if x > maximum' then x else maximum' where maximum' = maximumwhere xs

我认为这两个程序相当等效,因为我认为 where 绑定(bind)仅用变量的内容替换变量。但是当我在 ghci 中运行它时,第一个比后者慢得多,特别是对于长度超过 25 的数组。可能是 where 绑定(bind)造成了巨大的性能差异,但我不知道为什么。谁能为我解释一下吗?

最佳答案

不,它们并不等同。 letwhere 引入 sharing ,这意味着该值仅被评估一次。编译器通常不会共享两个相同表达式的结果,除非您告诉它,因为它通常无法自行判断这样做的时空权衡是否有利。

因此,您的第一个程序每次迭代将执行两次递归调用,使其 O(2^n),而第二个程序每次迭代仅执行一次,即 O(n).这些之间的差异是巨大的。在 n = 25 时,第一个程序导致超过 3300 万次递归调用,而第二个程序仅执行 25 次。

所以这个故事的寓意是,如果您想要共享,您需要使用 letwhere 来请求。

关于haskell - 在 Haskell 中,性能和绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8688719/

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