How to force evaluation in Haskell?

后端 未结 2 1680
难免孤独
难免孤独 2020-12-08 14:30

I am relatively new to Haskell and I am trying to learn how different actions can be executed in sequence using the do notation. In particular, I am writing a program to ben

相关标签:
2条回答
  • 2020-12-08 14:39

    Answer originally given by user ysdx on programmers:

    Indeed you version will not benchmark your algorithm. As r is not used it will not be evaluated at all.

    You should be able to do it with DeepSeq:

    benchmark :: [String] -> IO Integer
    benchmark inputList = do
                         start <- getCPUTime
                         let r = foo inputList
                         end <- r `deepseq` getCPUTime
                         return (end - start)
    

    (a `deepseq` b) is some "magic" expression which forces the complete/recursive evaluation of a before returning b.

    0 讨论(0)
  • 2020-12-08 14:56

    I would use the language extension -XBangPatterns, I find that quite expressive in such situations. So you would have to say "let !r = foo inputList" as in:

    {-# LANGUAGE BangPatterns #-}
    import System.CPUTime
    
    benchmark :: [String] -> IO Integer
    benchmark inputList = do
                             start <- getCPUTime
                             let !r = foo inputList
                             end <- getCPUTime
                             return (end - start)
    
    0 讨论(0)
提交回复
热议问题