gpt4 book ai didi

haskell - 选择转到元组的一侧时出现重复的实例

转载 作者:行者123 更新时间:2023-12-01 05:21:56 25 4
gpt4 key购买 nike

我想做的是这样的:

data MyDataType = MyDataType

class HasSpecialField a where
specialField :: a -> ByteString

instance HasSpecialField a => HasSpecialField (a, b) where
specialField (a, b) = specialField a

instance HasSpecialField b => HasSpecialField (a, b) where
specialField (a, b) = specialField b

instance HasSpecialField MyDataType where
specialField _ = "Coolio"

也就是说,如果你有一个像这样的元组:
myTuple :: (String, (Int, MyDataType))

然后你可以运行 specialField myTuple返回“Coolio”。

有没有办法做到这一点?

最佳答案

Data可用于完成此操作,但不会将函数限制为仅会成功的类型,从而将条件推迟到运行时。

{-# LANGUAGE DeriveDataTypeable #-}
import Control.Applicative

import Data.Generics

data MyDataType = MyDataType deriving (Typeable, Data)

specialField :: Data a => a -> Maybe String
specialField = fmap (\ MyDataType -> "Coolio") . something gfindtype

关于haskell - 选择转到元组的一侧时出现重复的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16005471/

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