Why does foldr use a helper function?

后端 未结 4 1952
旧时难觅i
旧时难觅i 2020-12-30 21:54

In explaining foldr to Haskell newbies, the canonical definition is

foldr            :: (a -> b -> b) -> b -> [a] -> b
foldr _ z          


        
4条回答
  •  温柔的废话
    2020-12-30 22:17

    As the comments say:

    -- Inline only in the final stage, after the foldr/cons rule has had a chance
    -- Also note that we inline it when it has *two* parameters, which are the
    -- ones we are keen about specialising!
    

    In particular, note the "we inline it when it has two parameters, which are the ones we are keen about specialising!"

    What this is saying is that when foldr gets inlined, it's getting inlined only for the specific choice of f and z, not for the choice of the list getting folded. I'm not expert, but it would seem it would make it possible to inline it in situations like

    map (foldr (+) 0) some_list
    

    so that the inline happens in this line and not after map has been applied. This makes it optimizable in more situations and more easily. All the helper function does is mask the 3rd argument so {-# INLINE #-} can do its thing.

提交回复
热议问题