gpt4 book ai didi

haskell - 使用类型类将值与 Haskell 中的类型相关联

转载 作者:行者123 更新时间:2023-12-03 14:39:14 24 4
gpt4 key购买 nike

我想使用类型类返回 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请求时,所讨论资源的路径段在功能上取决于从请求返回的数据类型。但是,在请求完成之前,我不会有这种类型的实例。

最佳答案

使用 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"

关于haskell - 使用类型类将值与 Haskell 中的类型相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54603849/

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