Lazy Evaluation and Time Complexity

前端 未结 7 549
走了就别回头了
走了就别回头了 2020-12-04 14:05

I was looking around stackoverflow Non-Trivial Lazy Evaluation, which led me to Keegan McAllister\'s presentation: Why learn Haskell. In slide 8, he shows the minimum functi

相关标签:
7条回答
  • 2020-12-04 14:50

    One interesting way of seeing this in practice is to trace the comparison function.

    import Debug.Trace
    import Data.List
    
    myCmp x y = trace (" myCmp " ++ show x ++ " " ++ show y) $ compare x y
    
    xs = [5,8,1,3,0,54,2,5,2,98,7]
    
    main = do
        print "Sorting entire list"
        print $ sortBy myCmp xs
    
        print "Head of sorted list"
        print $ head $ sortBy myCmp xs
    

    First, notice the way in which the output of the entire list is interleaved with the trace messages. Second, notice how the trace messages are similar when merely computing the head.

    I've just run this through Ghci, and its not exactly O(n): it takes 15 comparisons to find the first element, not the 10 that ought to be required. But its still less than O(n log n).

    Edit: as Vitus points out below, taking 15 comparisons instead of 10 is not the same as saying its not O(n). I just meant that it takes more than the theoretical minimum.

    0 讨论(0)
提交回复
热议问题