You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Web/Types中添加CanSelect实例?Haskell类型错误求助

问题:将CanSelect User实例移至Web/Types.hs时的类型错误修复

我正在开发一款预约预订程序,包含时间段功能。最初在Web/View/Timeslots/New.hs中为表单selectField创建了如下CanSelect User实例:

instance CanSelect User where
    type SelectValue User = Id User
    selectValue user = get #id user
    selectLabel user = get #displayName user

为减少代码重复,尝试将该实例移至Web/Types.hs,但粘贴后出现错误:

Web/Types.hs:17:10: error:
Not in scope: type constructor or class `CanSelect'
|
17 | instance CanSelect User where
| ^^^^^^^^^

随后尝试在Web/Types.hs中自行定义CanSelect类,又出现类型错误:

class CanSelect model where
    type SelectValue model :: Id model
    selectLabel :: model -> Text
    selectValue :: model -> Id model

instance CanSelect User where
    type SelectValue User = Id User
    selectValue user = get #id user
    selectLabel user = get #displayName user

错误信息:

  • Couldn't match kind *' with Id "users"'
    • Expected kind Id User', but Id User' has kind `*'
      • In the type Id User' In the type instance declaration for SelectValue'
      • In the instance declaration for `CanSelect User'

解决方法

1. 正确引入框架提供的CanSelect类

CanSelect类通常是由你使用的Web框架(如IHP)内置提供的,无需自行定义。在Web/Types.hs顶部导入对应模块:

import IHP.Form.Types (CanSelect(..), SelectValue)

(若使用其他框架,替换为对应框架的CanSelect类导入路径)

2. 确保依赖类型与函数在作用域内

在Web/Types.hs中,需保证User、Id类型及get函数可被访问:

import IHP.ModelSupport (Id, get)
import Generated.Types (User) -- 若User为自动生成类型,根据实际路径调整

3. 重新添加CanSelect User实例

完成导入后,直接将原实例代码粘贴到Web/Types.hs中即可:

instance CanSelect User where
    type SelectValue User = Id User
    selectValue user = get #id user
    selectLabel user = get #displayName user

错误原因解析

自行定义CanSelect类时的核心错误在于关联类型的kind声明错误:

type SelectValue model :: Id model

Id model是具体类型(kind为*),但关联类型的kind需指定为类型种类(如Type),而非具体类型。框架内置的CanSelect类正确定义类似:

class CanSelect a where
    type SelectValue a :: Type
    selectValue :: a -> SelectValue a
    selectLabel :: a -> Text

因此直接导入框架提供的类即可,无需自行实现。


内容的提问来源于stack exchange,提问作者adon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 08:42:22