Lazy Evaluation and Time Complexity

前端 未结 7 575
走了就别回头了
走了就别回头了 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:25

    Suppose minimum' :: (Ord a) => [a] -> (a, [a]) is a function that returns the smallest element in a list along with the list with that element removed. Clearly this can be done in O(n) time. If you then define sort as

    sort :: (Ord a) => [a] -> [a]
    sort xs = xmin:(sort xs')
        where
          (xmin, xs') = minimum' xs
    

    then lazy evaluation means that in (head . sort) xs only the first element is ever computed. This element is, as you see, simply (the first element of) the pair minimum' xs, which is computed in O(n) time.

    Of course, as delnan points out, the complexity depends on the implementation of sort.

提交回复
热议问题