Haskell Strict Lines

There is no exception when defining a lazy field until you print it.

> 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

With a strict field ( !Int), I thought that it undefinedwould be evaluated immediately, which would throw an exception, but in fact it would not be evaluated anyway before it was printed. Why is this?

> 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
+4
source share
1 answer

Since letit determines lazy binding itself, it letnever evaluates anything on its own (if not used BangPatterns).

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

You can tell the difference between strict and lazy constructors:

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

Source: https://habr.com/ru/post/1694278/


All Articles