Test if a value has been evaluated to weak head normal form

前端 未结 4 1158
故里飘歌
故里飘歌 2021-02-07 06:59

In Haskell, is it possible to test if a value has been evaluated to weak head normal form? If a function already exists, I would expect it to have a signature like



        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-07 07:09

    I'm not sure that there's anything pre-packaged for this. However, one can code it up:

    import Data.IORef
    import System.IO.Unsafe
    
    track :: a -> IO (a, IO Bool)
    track val = do
        ref <- newIORef False
        return
            ( unsafePerformIO (writeIORef ref True) `seq` val
            , readIORef ref
            )
    

    Here's an example usage in ghci:

    *NFTrack> (value, isEvaluated) <- track (undefined:undefined)
    *NFTrack> isEvaluated
    False
    *NFTrack> case value of _:_ -> "neat!"
    "neat!"
    *NFTrack> isEvaluated
    True
    

    Of course, this will be tracking whether the wrapped write-and-then-return-the-original-value thunk is evaluated to WHNF, not whether the thing passed to track is evaluated to WHNF, so you'll want to put this as close to the thunk you're interested in as possible -- e.g. it will not be able to tell you whether a thunk made by somebody else has already been evaluated by somebody else before the tracking started. And of course consider using MVar instead of IORef if you need thread-safety.

提交回复
热议问题