gpt4 book ai didi

haskell - 嵌套的模糊类型方法

转载 作者:行者123 更新时间:2023-12-02 05:32:31 25 4
gpt4 key购买 nike

假设我有课

class T where
tag1 :: String
tag2 :: String

启用模糊类型后,我可以在一个实例中指定它们中的每一个:

instance T A where
tag1 = "tag1"
tag2 = "tag2"

如果我想让tag2附加一些东西到tag1,我可以定义

instance T A where 
tag1 = "tag1"
tag2 = tag1 @A ++ " suffix"

这很好用,但如果我希望 tag2 始终将 suffix 附加到每个 tag1,我似乎必须指定模棱两可的调用对于每个实例。

我理解这样做的必要性,因为来自任何实例的 tag1 都适用于每次调用。但是,haskell 中有什么技巧可以让我只指定一次吗?

有点像

tag2 :: T a => String
tag2 = tag1 @a ++ " suffix"

最佳答案

您的代码目前无法编译,因为类型类没有类型参数,所以我假设您的代码实际上是(假设启用了 AllowAmbiguousTypes)

class T a where
tag1 :: String
tag2 :: String

现在您可以为 tag2 提供默认实现:

class T a where
tag1 :: String
tag2 :: String
tag2 = "tag2"

但这不符合tag1后缀的要求。
我们可以试试这个(假设启用了 TypeApplications):

class T a where
tag1 :: String
tag2 :: String
tag2 = tag1 @a ++ "suffix"

现在这个不会编译,编译错误会是

error: Not in scope: type variable `a'

没错,a 类型没有在任何地方定义。然而,我们想要引用类头部的a,为此我们需要语言扩展ScopedTypeVariables。 ,然后代码将编译,你会得到你期望的结果(我建议阅读链接文档)

这是一个演示用法的完整程序:

{-# LANGUAGE TypeApplications, AllowAmbiguousTypes, ScopedTypeVariables #-}

class T a where
tag1 :: String
tag2 :: String
tag2 = tag1 @a ++ " suffix"

data A = A
data B = B

instance T A where
tag1 = "tagA"

instance T B where
tag1 = "tagB"
tag2 = "tagB overriden"

main = do
putStrLn $ tag1 @A
putStrLn $ tag2 @A
putStrLn $ tag1 @B
putStrLn $ tag2 @B

输出是:

> ./foo
tagA
tagA suffix
tagB
tagB overriden

关于haskell - 嵌套的模糊类型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54966004/

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