Haskell严格的字段

时间:2018-03-01 07:09:58

标签: haskell

定义惰性字段时,在打印之前没有异常。

> data T = T Int deriving (Show)
> let t = T undefined
> t
T *** Exception: Prelude.undefined
CallStack (from HasCallStack):
  error, called at libraries/base/GHC/Err.hs:79:14 in base:GHC.Err
  undefined, called at <interactive>:3:7 in interactive:Ghci3

使用严格字段(!Int),我认为会立即评估undefined,这会导致异常,但实际上,在打印之前它仍然没有评估。那是为什么?

> data X = X !Int deriving (Show)
> let x = X undefined
> x
*** Exception: Prelude.undefined
CallStack (from HasCallStack):
  error, called at libraries/base/GHC/Err.hs:79:14 in base:GHC.Err
  undefined, called at <interactive>:6:11 in interactive:Ghci5

1 个答案:

答案 0 :(得分:8)

因为let本身定义了一个惰性绑定 - let从不自行评估任何内容(除非使用BangPatterns)。

ghci> let x = undefined
ghci> x
*** Exception: Prelude.undefined

你可以区分严格和懒惰的构造函数,如:

ghci> T undefined `seq` ()
()
ghci> X undefined `seq` ()
*** Exception: Prelude.undefined