gpt4 book ai didi

haskell - 与 Haskell 类型类中的类型匹配

转载 作者:行者123 更新时间:2023-12-02 10:17:48 25 4
gpt4 key购买 nike

我不知道如何准确地表达它,所以如果有人有一个好名字,请告诉我。

我正在尝试编写一个名为 Matchable 的类型类。这个想法是我拥有的几种不同类型的正则表达式(RegExp aComplexRegex a)应该能够在输入上匹配。

所以我尝试了这个:

class Matchable a where
-- regex, input, success
match :: a -> b -> Bool

但我真正想要的是使用类型构造函数变量或其他东西来解构类型类中的构造函数:

class Matchable a where
-- regex, input, success
match :: (B a) -> [a] -> Bool

这样我就可以让 RegExp CharComplexRegex Char 都在 String 上匹配。有什么办法可以做到这一点吗?谢谢。

最佳答案

为了简单起见,为什么不直接让 Matchable 的类变量具有 * -> * 类型呢? (有关其他示例,请参阅 Functor、Applicative、Monad、Foldable、Traversable更高年级)。

class Matchable b where
-- regex, input, success
match :: b a -> [a] -> Bool

instance Matchable ComplexRegex where
-- match :: ComplexRegex a -> [a] -> Bool
match = error "unimplemented"

instance Matchable RegExp where
-- match :: RegExp a -> [a] -> Bool
match = error "unimplemented"

然后,您可以将 String ~ [Char]ComplexRegex CharRegExp Char 进行匹配。

关于haskell - 与 Haskell 类型类中的类型匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44337541/

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