关于 Foldable Maybe 实例的问题

Question about the Foldable Maybe instance

资料来源:赫顿,格雷厄姆。 “在 Haskell 中编程”(第 267 页)

  1. Show how the Maybe type can be made foldable and traversable, by giving explicit definitions for fold, foldMap, foldr, foldl and traverse.

我做了foldr定义。为了检查我的解决方案,我在网上找到了这段代码:

 -- foldr :: (a -> b -> b) -> b -> Maybe a -> b
    foldr _ _ Nothing = mempty
    foldr f v (Just a) = f a v

似乎应该在基本情况下返回累加器(而不是 mempty)。是这样吗?

是的,您正在查看的代码是伪造的,甚至无法编译。它应该按照你说的做:

foldr _ v Nothing = v

请注意,除非作为练习,否则您实际上不需要完成所有这些手动工作。你可以只写

{-# language DeriveTraversable #-}
module MyModule where
import Prelude hiding (Maybe (..))
data Maybe a = Nothing | Just a
  deriving (Show, Eq, Ord, Functor, Foldable, Traversable)

并完成它。如果你不想依赖语言扩展,那么你仍然只需要写一个方法:traverse。你可以写

import Prelude hiding (Maybe (..))
import Data.Traversable

data Maybe a = Nothing | Just a deriving (Show, Eq)

instance Foldable Maybe where
  foldMap = foldMapDefault
instance Functor Maybe where
  fmap = fmapDefault
instance Traversable Maybe where
  traverse _ Nothing = _1 -- fill in the blanks
  traverse f (Just a) = _2

Maybe 的情况下,这应该会产生所有 class 方法的最佳定义。对于某些类型,您需要手动编写一些方法以获得最佳结果。例如,默认值通常不会为递归类型给出 <$ 的良好定义。