gpt4 book ai didi

haskell - Haskell 中相同的 LHS,不同的 RHS

转载 作者:行者123 更新时间:2023-12-04 03:41:30 24 4
gpt4 key购买 nike

我需要解决的问题是:

使用 foldMap 为可折叠类型编写一个过滤器函数。

filterF 
:: ( Applicative f
, Foldable t
, Monoid (f a)
)
=> (a->Bool) -> t a -> f a
filterF=undefined

对于以下所有测试,该函数应返回 True:

unit_testFilterF1 = filterF Data.Char.isUpper "aNA aRe mEre" == "NARE"
unit_testFilterF1 = filterF Data.Char.isUpper "aNA aRe mEre" == First (Just 'N')
unit_testFilterF1 = filterF Data.Char.isUpper "aNA aRe mEre" == Min 'A'
unit_testFilterF1 = filterF Data.Char.isUpper "aNA aRe mEre" == Max 'R'
unit_testFilterF1 = filterF Data.Char.isUpper "aNA aRe mEre" == Last (Just 'E')

根据老师给我们的提示,我写了这个解决方案:

filterF 
:: ( Applicative f
, Foldable t
, Monoid (f a)
)
=> (a-> Bool) -> t a -> f a
filterF funct u= foldMap (\x -> if funct x then pure x else mempty) u

请注意,我显然没有完全理解这个解决方案,因为我无法弄清楚为什么这些测试会返回 True。我的理解是:

  • filterF 接收 2 个参数:funct(接受类型为 a 的参数并返回 Bool 的函数)和 u (可折叠的幺半群)
  • 我们让 functu 中的每个元素决定它是否应该保留。如果它确实存在,我们将其“提升”到具有 pure
  • Applicative 的“级别”
  • 然后我们使用 f
  • 的幺半群状态定义的操作将所有元素组合成一个

鉴于在测试中我们有相同的 LHS 和不同的 RHS,我猜测 RHS 会影响 f 的结构。有点像我们的做法:

unit_testFilterF6=filterF Data.Char.isUpper"aNA aRe mEre" :: First Char

有人可以进一步解释这里发生了什么吗?我是 Haskell 初学者。

最佳答案

让我们写f对于 (\x -> if funct x then pure x else mempty) , 当 functData.Char.isUpper .

我们可以评估filterF Data.Char.isUpper "aNA aRe mEre"如下:

filterF Data.Char.isUpper "aNA aRe mEre"
= -- definition of filterF
folMap f "aNA aRe mEre"
= -- definition of foldMap
f 'a' <> f 'N' <> f 'A' <> f ' ' <> f 'a' <> f 'R' <> ....
= -- definition of f
mempty <> pure 'N' <> pure 'A' <> mempty <> mempty <> pure 'R' <> ...
= -- monoidal laws
pure 'N' <> pure 'A' <> pure 'R' <> pure 'E'

从这里开始,使用 <> 的定义从你提到的几个幺半群,你应该可以得出结论。

关于haskell - Haskell 中相同的 LHS,不同的 RHS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65952082/

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