由于使用了类型(行类型),类型类实例头无效

WHI*_*LOR 1 purescript

我需要为记录类型定义一个简单的类型类和实例:

class Codable param where
  getCodec :: Codec param


type Obj = { id :: String }

instance Codable Obj where
  getCodec = objCodec

Run Code Online (Sandbox Code Playgroud)

尽管在定义记录类型的实例时出现错误:

 Type class instance head is invalid due to use of type

    ( id :: string
    )

 All types appearing in instance declarations must be of the form T a_1 .. a_n, where each type a_i is of the same form, unless the type is fully determined by other type class arguments via functional dependencies.
Run Code Online (Sandbox Code Playgroud)

但这个消息对我来说听起来很神秘。有人可以详细说明吗?在这种情况下该怎么办?

Fyo*_*kin 5

PureScript 只是不支持行实例,仅此而已。

如果您不知道,大括号语法是将Record构造函数应用于类型行的语法糖,即{ id :: String }相当于Record ( id :: String ).

通常的解决方法是将您的记录包装在newtype

newtype Obj = Obj { id :: String }

instance Codable Obj where ...
Run Code Online (Sandbox Code Playgroud)

或者,如果您确实想为所有类型的记录提供编解码器(类似的purescript-argonaut做法),您可以将行转换为RowList,然后对其进行类型级匹配。这是一种高威力、高难度的技巧,我现在不准备详细解释,但这里有一个例子这里还有一个例子。这与中使用的相同purescript-argonaut