gpt4 book ai didi

haskell - 等价于 Functor 或 Foldable 对于更高种类的类型

转载 作者:行者123 更新时间:2023-12-04 01:03:52 28 4
gpt4 key购买 nike

考虑这段代码,使用 FunctorFoldable 类型类:

{-# LANGUAGE DeriveFunctor, DeriveFoldable #-}

data Foo a = Foo (Maybe a) [a] deriving(Show, Functor, Foldable)

fmap (+1) (Foo (Just 1) [2,3,4]) -- result: Foo (Just 2) [3,4,5]
sum (Foo (Just 1) [2,3,4]) -- result: 10

是否有一些类似的类型类集可以对更高种类的类型参数进行操作?例如:

data Bar a = Bar (a Int) (a Bool)

somethingLikeFmap :: forall t f g. SomethingLikeFunctor t => (forall a. f a -> g a) -> t f -> t g

somethingLikeAll :: forall t f. SomethingLikeFoldable t => (forall a. f a -> Bool) -> t f -> Bool

somethingLikeFmap listToMaybe (Bar [1,2,3] [False, True]) -- desired result: Bar (Just 1) (Just False)
somethingLikeAll null (Bar [1,2,3] [False, True]) -- desired result: False
somethingLikeAll null (Bar [] []) -- desired result: True

最佳答案

我怀疑您正在寻找 rank2classes .例如:

{-# LANGUAGE FlexibleInstances, StandaloneDeriving, TemplateHaskell #-}

import Data.Maybe
import Data.Monoid
import qualified Rank2
import qualified Rank2.TH

data Bar a = Bar (a Int) (a Bool)
deriving instance Show (Bar Maybe)
Rank2.TH.deriveFunctor ''Bar
Rank2.TH.deriveFoldable ''Bar

main = do
print $ Rank2.fmap listToMaybe (Bar [1,2,3] [False, True])
print $ getAll (Rank2.foldMap (All . null) (Bar [1,2,3] [False, True]))
print $ getAll (Rank2.foldMap (All . null) (Bar [] []))

编辑: 或者可能是 mmorph ,尽管我怀疑 rank2classes 可能对您更有用。

关于haskell - 等价于 Functor 或 Foldable 对于更高种类的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67171533/

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