1. 首页
  2. 其他

当 Tree 实现可折叠 foldMap 时,Foldr/Foldl 免费?

本文介绍了当 Tree 实现可折叠 foldMap 时,Foldr/Foldl 免费?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Haskell 的初学者,正在学习Learn You a Haskell”.

I am a beginner at Haskell and learning from “Learn You a Haskell”.

关于FoldableTree 实现,我有些不明白.

There’s something I don’t understand about the Tree implementation of Foldable.

instance F.Foldable Tree where  
    foldMap f Empty = mempty  
    foldMap f (Node x l r) = F.foldMap f l `mappend`  
                             f x           `mappend`  
                             F.foldMap f r  

引自 LYAH:因此,如果我们只是为某种类型实现 foldMap 我们会得到 foldrfoldl在那种类型上免费!”.

Quote from LYAH: “So if we just implement foldMap for some type, we get foldr and foldl on that type for free!”.

有人能解释一下吗?我不明白我现在如何以及为什么免费获得 foldrfoldl

Can someone explain this? I don’t understand how and why do I get foldr and foldl for free now…

推荐答案

foldr 总是可以定义为:

foldr can always be defined as:

foldr f z t = appEndo (foldMap (Endo . f) t) z

其中 appEndo 和 Endo 只是新型解包器/包装器.事实上,这段代码是直接从 Foldable 类型类中提取出来的.所以,通过定义foldMap,你会自动得到foldr.

where appEndo and Endo are just newtype unwrappers/wrappers. In fact, this code got pulled straight from the Foldable typeclass. So, by defining foldMap, you automatically get foldr.

这篇关于当 Tree 实现可折叠 foldMap 时,Foldr/Foldl 免费?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2

当 Tree 实现可折叠 foldMap 时,Foldr/Foldl 免费? 为WP2原创文章,链接:https://www.wp2.cn/other/%e5%bd%93-tree-%e5%ae%9e%e7%8e%b0%e5%8f%af%e6%8a%98%e5%8f%a0-foldmap-%e6%97%b6%ef%bc%8cfoldr-foldl-%e5%85%8d%e8%b4%b9/