How does seq force functions?

不问归期 提交于 2019-12-09 04:13:26

问题


Background

This question arises from a challenge Brent Yorgey posed at OPLSS: write a function f :: (Int -> Int) -> Bool that distinguishes f undefined from f (\x -> undefined). All of our answers either used seq or something like bang patterns that desugar into seq. For example:

f :: (Int -> Int) -> Bool
f g = g `seq` True

*Main> f undefined
*** Exception: Prelude.undefined
*Main> f (\x -> undefined)
True

The GHC commentary on seq says that

e1 `seq` e2 

used to desugar into

case e1 of { _ -> e2 }

so I tried desugaring manually. It didn't work:

f' g = case g of { _ -> True }

*Main> f' undefined
True
*Main> f' (\x -> undefined)
True

Question

Does this behavior depend on the more complex seq described at the end of the commentary, and if so, how does it work? Could such an f be written without these primitives?

x  `seq` e2 ==> case seq# x RW of (# x, _ #) -> e2    -- Note shadowing!
e1 `seq` e2 ==> case seq# x RW of (# _, _ #) -> e2

回答1:


There is a more higher-level description of STG-machine in How to make a fast curry: push/enter vs eval/apply

Figure 2 contains rule CASEANY that works for functions. In this paper "is a value" proposition means either:

  • it is a saturated constructor application
  • it is a function
  • it is a partial function application (which is still a function, semantically)

Unboxed values, including literals are treated specially, more information can be found in Unboxed values as first class citizens

All these are implementation details and are hidden inside compiler (GHC). Haskell's case expression doesn't force it's scrutineer, only pattern-matching and seq do.




回答2:


seq cannot be implemented in Haskell. Instead, it is a primitive "hook" into evaluation to weak-head normal form in whatever runtime your Haskell is running on. E.g. on GHC it is compiled to a case in GHC Core, which triggers evaluation to the outermost constructor.

Since it can't be implemented in pure Haskell, it is defined (in GHC) as a primop:

pseudoop   "seq"
       a -> b -> b
       { Evaluates its first argument to head normal form, and then returns its second
         argument as the result. }

Since functions don't have a normal form, seq halts evaluation once it reaches one.

Magically available to the compiler. The same goes for other primitives like par or unsafeCoerce, the RealWorld token, forkOn and so on. All the useful stuff.



来源:https://stackoverflow.com/questions/6442019/how-does-seq-force-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!