foldl is tail recursive, so how come foldr runs faster than foldl?

后端 未结 7 1409
無奈伤痛
無奈伤痛 2020-11-27 10:42

I wanted to test foldl vs foldr. From what I\'ve seen you should use foldl over foldr when ever you can due to tail reccursion optimization.

This makes sense. Howeve

7条回答
  •  我在风中等你
    2020-11-27 11:04

    Well, let me rewrite your functions in a way that difference should be obvious -

    a :: a -> [a] -> [a]
    a = (:)
    
    b :: [b] -> b -> [b]
    b = flip (:)
    

    You see that b is more complex than a. If you want to be precise a needs one reduction step for value to be calculated, but b needs two. That makes the time difference you are measuring, in second example twice as much reductions must be performed.

    //edit: But time complexity is the same, so I wouldn't bother about it much.

提交回复
热议问题