gpt4 book ai didi

purescript - 可折叠树型, "value of instance is undefined here, so this reference is not allowed"

转载 作者:行者123 更新时间:2023-12-03 13:11:54 25 4
gpt4 key购买 nike

定义如下简单的树结构后

data Tree a = Leaf | Branch (Tree a) a (Tree a)

我尝试定义一个 Foldable例如,仅定义 foldMap并使用 foldrDefaultfoldlDefault职能:
instance treeFoldableInstance :: Foldable Tree where
foldr = foldrDefault
foldl = foldlDefault
foldMap f Leaf = mempty
foldMap f (Branch left a right) = foldMap f left <> (f a) <> foldMap f right

然而,这会导致:
The value of treeFoldableInstance is undefined here, so this reference is not allowed.

当我定义 foldlfoldr明确地,它编译。这个错误的文档告诉我关于懒惰,但这如何适用于这里?

最佳答案

这是因为使用了 foldlDefaultfoldrDefault需要您正在尝试构建的字典,并且由于 PureScript 被严格评估,这是不可能的。

可能最简单的解决方法是尝试以下方法:

instance treeFoldableInstance :: Foldable Tree where
foldr f = foldrDefault f
foldl f = foldlDefault f
foldMap f Leaf = mempty
foldMap f (Branch left a right) = foldMap f left <> (f a) <> foldMap f right

通过 eta 扩展 foldrfoldl定义,它会延迟自引用,因为脱糖后的代码变得类似于:
foldr = \f -> foldrDefault treeFoldableInstance f

所以引用 treeFoldableInstance仅在 f 之后评估传入,而不是在 treeFoldableInstance 的声明期间.

关于purescript - 可折叠树型, "value of instance is undefined here, so this reference is not allowed",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38488456/

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