How does seq force functions?

前端 未结 2 816
离开以前
离开以前 2021-02-02 10:05

Background

This question arises from a challenge Brent Yorgey posed at OPLSS: write a function f :: (Int -> Int) -> Bool that distinguishes f

2条回答
  •  走了就别回头了
    2021-02-02 10:18

    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.

提交回复
热议问题