gpt4 book ai didi

performance - Haskell 中的隐式模式匹配

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

人们应该期待这两个 empty 之间的性能差异,还是仅仅是风格偏好的问题?

foo list = case list of
[] -> True
(_ : _) -> False

bar list = case list of
(_ : _) -> False
_ -> True

最佳答案

一般来说,您不应该期望性能会在像您所询问的那样琐碎的摆弄模式之间发生可预测的变化,并且通常可以期望生成的代码是相同的。

但实际检查的方法是查看核心和/或标准基准。在这种情况下,生成的代码是相同的,实际上 GHC 似乎实际上将它们组合在一起:

我编译了上面的片段

ghc -Wall -O2 -ddump-to-file -ddump-simpl -dsuppress-module-prefixes -dsuppress-uniques -fforce-recomp  YourCode.hs

我们看到了这个核心:

foo :: forall t. [t] -> Bool
[GblId,
Arity=1,
Caf=NoCafRefs,
Str=DmdType <S,1*U>,
Unf=Unf{Src=InlineStable, TopLvl=True, Value=True, ConLike=True,
WorkFree=True, Expandable=True,
Guidance=ALWAYS_IF(arity=1,unsat_ok=True,boring_ok=False)
Tmpl= \ (@ t) (list [Occ=Once!] :: [t]) ->
case list of _ [Occ=Dead] {
[] -> True;
: _ [Occ=Dead] _ [Occ=Dead] -> False
}}]
foo =
\ (@ t) (list :: [t]) ->
case list of _ [Occ=Dead] {
[] -> True;
: ds ds1 -> False
}

-- RHS size: {terms: 1, types: 0, coercions: 0}
bar :: forall t. [t] -> Bool
[GblId,
Arity=1,
Caf=NoCafRefs,
Str=DmdType <S,1*U>,
Unf=Unf{Src=InlineStable, TopLvl=True, Value=True, ConLike=True,
WorkFree=True, Expandable=True,
Guidance=ALWAYS_IF(arity=1,unsat_ok=True,boring_ok=False)
Tmpl= \ (@ t) (list [Occ=Once!] :: [t]) ->
case list of _ [Occ=Dead] {
[] -> True;
: _ [Occ=Dead] _ [Occ=Dead] -> False
}}]
bar = foo

我认为 Tmpl 是在其他模块中为内联而公开的原始实现,但我不确定。

关于performance - Haskell 中的隐式模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42612107/

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