gpt4 book ai didi

haskell - 指头复杂度

转载 作者:行者123 更新时间:2023-12-04 15:45:17 25 4
gpt4 key购买 nike

我刚刚在看 Apfelmus' excellent introduction to Finger Trees第二次开始怀疑他对 head 的实现:

import Prelude hiding (head)

data Tree v a = Leaf v a
| Branch v (Tree v a) (Tree v a)

toList :: Tree v a -> [a]
toList (Leaf _ a) = [a]
toList (Branch _ x y) = toList x ++ toList y

head :: Tree v a -> a
head (Leaf _ a) = a
head (Branch _ x _) = head x

由于相互实现函数是一种很好的重用代码的方式,这让我开始思考以下实现是否会像他的原始实现一样高效(复杂性明智):
import Prelude -- not needed, just for making it obvious
data Tree v a = Leaf v a
| Branch v (Tree v a) (Tree v a) deriving Show

toList :: Tree v a -> [a]
toList (Leaf _ a) = [a]
toList (Branch _ x y) = toList x ++ toList y

head' :: Tree v a -> a
head' = head . toList

惰性求值和原始实现一样有效吗?

最佳答案

是的,headhead'如果交给 GHC,应该具有相同的时间复杂度。我希望有一个小的常数因子差异有利于 head (也许有 60% 的信心 - 列表融合优化的东西在工作时非常疯狂)。

关于haskell - 指头复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56061160/

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