gpt4 book ai didi

class - Haskell 单体可折叠玫瑰树

转载 作者:行者123 更新时间:2023-12-03 15:04:43 25 4
gpt4 key购买 nike

我需要为玫瑰树数据结构制作一个可折叠的实例:

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

使用以下幺半群和玫瑰相关的类/实例:
instance Functor Rose where
fmap f (a :> bs) = (f a) :> (map (fmap f) bs)

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

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

我尝试了什么:
instance Foldable Rose where
fold (a:>b) = a <> (foldMap fold b)

但是,这无法正常工作,对于系统检查,我收到错误:
*** Failed! Exception: 'Prelude.undefined': 
[] :> []

但是我不确定为什么它不起作用,有人可以帮我吗?

提前致谢!

此致,
斯凯菲。

最佳答案

您对 fold 的实现是正确的,没有理由改变它。

问题是 fold不足以定义 Foldable .来自 the documentation :

class Foldable t where Source

Data structures that can be folded.

Minimal complete definition: foldMap or foldr.



所以你必须定义 foldMapfoldr (或两者)。定义 foldMap更容易、更自然(在许多情况下也更有效)。所以你应该写这样的东西:
import Data.Foldable
import Data.Monoid

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

instance Foldable Rose where
foldMap f (x :> xs) = f x <> foldMap (foldMap f) xs

关于class - Haskell 单体可折叠玫瑰树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26257369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com