代码之家  ›  专栏  ›  技术社区  ›  sof

简单的例子来阐明记忆和严格

  •  1
  • sof  · 技术社区  · 7 年前

    1.

    ghci> let x = trace "one" 1 in (x, x)
    
    (one
    1,one
    1)
    

    我预料到了 let-expr x ,因此结果如下所示:

    (one
    1,1)
    

    ghci> let !x = undefined in 1
    
    ...
    error
    ...
    

    好吧,严格评估 bang-pattern

    ghci> let !x = trace "one" 1 in 1
    
        1
    

    one
    1
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   Alexis King    7 年前

    自GHC 7.8.1以来 monomorphism restriction x 绑定被泛化为一个多态的,类型类约束的绑定

    x :: Num a => a
    

    自从 1 是多态数。即使此类型不包含任何函数箭头( -> Num typeclass字典并使用它来构造其结果。

    ghci> let x = trace "one" (1 :: Integer) in (x, x)
    (one
    1,1)
    ghci> let !x = trace "one" (1 :: Integer) in 1
    one
    1
    

    通常,前面提到的单态限制是适当的,正是为了防止这种混淆,即在语法上是值定义的绑定可以多次评估其RHS。链接的答案描述了限制的一些折衷,但是如果您愿意,可以重新打开它,这将使您的原始示例达到您所期望的效果:

    ghci> :set -XMonomorphismRestriction
    ghci> let x = trace "one" 1 in (x, x)
    (one
    1,1)
    ghci> let !x = trace "one" 1 in 1
    one
    1
    
    推荐文章