我想使用类型类返回String
功能上依赖于 Haskell 类型的实例。例如,假设我们有这样的类型Form
。我想将字符串“form”与此类型相关联。给定类型Invocation
,我想关联字符串“job”。等等。重要的是我通常不会有相关类型的实例,尽管该类型将位于使用它的任何函数的类型签名中。
也许证明这一点的一个简单方法是使用 Swift:
protocol Resource {
static var resourcePathSegment: String { get }
}
struct Form : Resource {
static let resourcePathSegment = "form"
}
struct Invocation: Resource {
static let resourcePathSegment = "job"
}
print(Form.resourcePathSegment)
我为什么想要这样的东西?我正在与使用某些约定的 REST API 进行对话。为一个GET
请求时,到相关资源的路径段在功能上取决于从请求返回的数据的类型。但是,在请求完成之前我不会获得此类型的实例。
Using TypeApplications
, 这很容易:
{-# LANGUAGE AllowAmbiguousTypes, TypeApplications #-}
class Resource a where
resourcePathSegment :: String
instance Resource Form where
resourcePathSegment = "form"
instance Resource Invocation where
resourcePathSegment = "job"
为了说明如何使用上面的内容:
ghci> :t resourcePathSegment
resourcePathSegment :: Resource a => String
ghci> resourcePathSegment @Form
"form"
ghci> resourcePathSegment @Invocation
"job"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)