gpt4 book ai didi

haskell - 如何将 [Maybe Text] 与镜头连接?

转载 作者:行者123 更新时间:2023-12-01 07:03:48 25 4
gpt4 key购买 nike

有什么办法可以用镜头写出以下内容...

[Maybe Text] -> Text

...这可能可以概括为:
(Monoid a, Traversable t) => t a -> a

我正在尝试做的一个具体例子:
[Just "abc", Nothing, Just "def"] -> "abcdef"
[Nothing, Nothing] -> ""

PS:我假设镜头有一些时髦的组合器来做到这一点。如果我被镜头的惊人效果蒙蔽了双眼,而这可以通过更简单的组合器轻松实现,请告诉我。

最佳答案

您的 (Monoid a, Traversable t) => t a -> a函数可以进一步推广到一个简单的 fold :: (Foldable f, Monoid a) => f a -> a .

例如:

Prelude> import Data.Foldable
Prelude Data.Foldable> fold [Just "abc", Nothing, Just "def"]
Just "abcdef"

我们可以从 Maybe 中解开它和:
import Data.Foldable(fold, mempty)
import Data.Maybe(maybe)

foldMaybe :: (Foldable f, Monoid a) => f (Maybe a) -> a
foldMaybe = fromMaybe mempty . fold

例如:
Prelude Data.Foldable Data.Maybe> foldMaybe [Just "abc", Nothing, Just "def"]
"abcdef"
Prelude Data.Foldable Data.Maybe> foldMaybe [Nothing] :: String
""

关于haskell - 如何将 [Maybe Text] 与镜头连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57991801/

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