【问题标题】:Reusing lists in patterns在模式中重用列表
【发布时间】:2011-07-09 19:58:07
【问题描述】:

当我写作时:

sort [x] = [x]

编译器是否足够聪明,可以重复使用相同的列表,还是我必须明确说明?

sort xs@[_] = xs

【问题讨论】:

    标签: list haskell performance pattern-matching reusability


    【解决方案1】:

    它足够聪明吗?让我们看看!

    ezyang@javelin:~$ cat Foo.hs
    module Foo where
    foo [x] = [x]
    

    这里是 STG:

    ezyang@javelin:~$ ghc --make Foo.hs -ddump-stg -fforce-recomp
    [1 of 1] Compiling Foo              ( Foo.hs, Foo.o )
    
    ==================== STG syntax: ====================
    Foo.foo =
        \r srt:(0,*bitmap*) [ds_sdP]
            let-no-escape {
              fail_sdO =
                  sat-only \r srt:(0,*bitmap*) [ds1_sdN]
                      Control.Exception.Base.patError "Foo.hs:2:0-12|function foo";
            } in 
              case ds_sdP of wild_sdY {
                [] -> fail_sdO GHC.Prim.realWorld#;
                : x_sdV ds1_sdT ->
                    case ds1_sdT of wild1_sdZ {
                      [] -> : [x_sdV GHC.Types.[]];
                      : ipv_se0 ipv1_se1 -> fail_sdO GHC.Prim.realWorld#;
                    };
              };
    SRT(Foo.foo): [Control.Exception.Base.patError]
    

    有趣的是这一行:

                      [] -> : [x_sdV GHC.Types.[]];
    

    我们看到我们正在为x_sdV[] 创建一个新的cons-cell。所以不行。不过这也不算太糟糕,因为x_sdV本身是共享的,所以它只是一个构造函数;此外,我们正在强制列表的主干xs,因此无论如何GHC 都需要重写它。所以不用担心。

    【讨论】:

    • +1 我完全不知道我在这里看到了什么,但它看起来确实令人印象深刻!
    • 是的,STG 读起来有点好笑。 : 表示 cons,[x1 x2 x3] 表示 cons 的参数(有两个,因为 cons 需要两个参数。)
    猜你喜欢
    • 2017-11-26
    • 2015-08-31
    • 2012-11-07
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 2019-07-04
    相关资源
    最近更新 更多