【问题标题】:Foldable and Monoid types可折叠和 Monoid 类型
【发布时间】:2018-10-12 12:07:08
【问题描述】:

我正在尝试编写函数,使用 monoids 和 Foldable 将列表中的所有元素相加和相乘。我设置了一些我认为可行的代码:

data Rose a = a :> [Rose a]
    deriving (Eq, Show)

instance Functor Rose where
    fmap f rose@(a:>b) = (f a :> map (fmap f) b) 

class Monoid a where
    mempty ::           a
    (<>)   :: a -> a -> a

instance Monoid [a] where
    mempty = []
    (<>)   = (++)

newtype Sum     a = Sum     { unSum     :: a } deriving (Eq, Show)
newtype Product a = Product { unProduct :: a } deriving (Eq, Show)

instance Num a => Monoid (Sum a) where
    mempty           = Sum 0
    Sum n1 <> Sum n2 = Sum (n1 + n2)

instance Num a => Monoid (Product a) where
    mempty                   = Product 1
    Product n1 <> Product n2 = Product (n1 * n2)

class Functor f => Foldable f where
    fold    :: Monoid m =>             f m -> m
    foldMap :: Monoid m => (a -> m) -> f a -> m
    foldMap f a = fold (fmap f a)

instance Foldable [] where
    fold = foldr (<>) mempty

instance Foldable Rose where
    fold (a:>[]) = a <> mempty
    fold (a:>b)  = a <> (fold (map fold b))

然后在定义了不同的 Foldable 实例以及 Sum 和 Product 类型之后,我想定义两个函数,它们分别添加乘以数据结构中的元素,但这会产生我不知道如何解释的错误,我必须承认我认为这是比实际逻辑更多的猜测工作,因此欢迎对您的答案进行全面解释。

fsum, fproduct :: (Foldable f, Num a) => f a -> a
fsum b     = foldMap Sum b
fproduct b = foldMap Product b

错误:

Assignment3.hs:68:14: error:
    * Occurs check: cannot construct the infinite type: a ~ Sum a
    * In the expression: foldMap Sum b
      In an equation for `fsum': fsum b = foldMap Sum b
    * Relevant bindings include
        b :: f a (bound at Assignment3.hs:68:6)
        fsum :: f a -> a (bound at Assignment3.hs:68:1)
   |
68 | fsum b     = foldMap Sum b
   |              ^^^^^^^^^^^^^

Assignment3.hs:69:14: error:
    * Occurs check: cannot construct the infinite type: a ~ Product a
    * In the expression: foldMap Product b
      In an equation for `fproduct': fproduct b = foldMap Product b
    * Relevant bindings include
        b :: f a (bound at Assignment3.hs:69:10)
        fproduct :: f a -> a (bound at Assignment3.hs:69:1)
   |
69 | fproduct b = foldMap Product b
   |              ^^^^^^^^^^^^^^^^^

【问题讨论】:

  • 您需要添加unSumunProduct 作为后处理步骤。

标签: haskell types monoids foldable


【解决方案1】:

如果您在foldMap 中使用Sum(或Product),您将首先将Foldable 中的项目映射Sums(或Products) )。因此fsum 的结果将——就像你定义的那样——是Sum a,而不是a

fsum :: (Foldable f, Num a) => f a -> Sum a
fsum b = foldMap Sum b

为了检索包装在 Sum 构造函数中的值,您可以使用 unSum :: Sum a -&gt; a getter 获取它:

fsum :: (Foldable f, Num a) => f a -> a
fsum b = unSum (foldMap Sum b)

或在eta-reduction之后:

fsum :: (Foldable f, Num a) => f a -> a
fsum = unSum . foldMap Sum

Product 也应该这样。

【讨论】:

    猜你喜欢
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    相关资源
    最近更新 更多