PureScript和类型类

Mic*_*ler 5 purescript

我在使用PureScript类型类时遇到了麻烦.我必须在前面说,我不是Haskell专家,所以如果这些是明显的错误我会道歉.

我已经尝试了几种不同的方法,并为每个方法打了一堵墙.我基本上试图为show图中的边定义函数.一种方法如下:

module Foo where

data Edge n = Edge { from :: n, to :: n }

instance showEdge :: (Show n) => Show (Edge n) where
  show e = "Edge from "++(show e.from)++" to "++(show e.to)

e = Edge { from: 1, to: 2 }

main = show e
Run Code Online (Sandbox Code Playgroud)

这给了我错误:

$ psc src/Attempt1.purs
Error at src/Attempt1.purs line 6, column 27:
Error in declaration showEdge
Cannot unify Prim.Object with Foo.Edge.
Run Code Online (Sandbox Code Playgroud)

我猜这与它推断e出定义中的类型这一事实有关show.我在这里尝试添加类型注释,但是我收到了语法错误:

module Foo where

data Edge n = Edge { from :: n, to :: n }

instance showEdge :: (Show n) => Show (Edge n) where
  show e :: Edge n
  show e = "Edge from "++(show e.from)++" to "++(show e.to)

e = Edge { from: 1, to: 2 }

main = show e
Run Code Online (Sandbox Code Playgroud)

我尝试的第二件事是:

module Foo where

type Edge n = { from :: n, to :: n }

instance showEdge :: (Show n) => Show (Edge n) where
  show e = "Edge from "++(show e.from)++" to "++(show e.to)

e :: Edge Number
e = { from: 1, to: 2 }

main = show e
Run Code Online (Sandbox Code Playgroud)

这给了我:

$ psc src/Attempt2.purs
Error at src/Attempt2.purs line 5, column 1:
Type synonym instances are disallowed
Run Code Online (Sandbox Code Playgroud)

所以我然后尝试明确列出基础类型:

module Foo where

type Edge n = { from :: n, to :: n }

instance showEdge :: (Show n) => Show { from :: n, to :: n } where
  show e = "Edge from "++(show e.from)++" to "++(show e.to)

e :: Edge Number
e = { from: 1, to: 2 }

main = show e
Run Code Online (Sandbox Code Playgroud)

这给了我:

$ psc src/Attempt3.purs
Error at src/Attempt3.purs line 5, column 1:
Error in type (to :: n, from :: n):
Type class instance head is invalid.
Run Code Online (Sandbox Code Playgroud)

我不知道"类型类实例头"是什么,所以我无处可去.

所有三次尝试均失败.可能出于完全不同的原因.作为PureScript的新手,我只是不知道问题是什么.我一直在尝试跟踪Data.*各种类型的示例并通过示例阅读PureScript.我无法弄清楚这一点.

谢谢你的帮助.

gb.*_*gb. 8

实际上,你的第一次尝试几乎就在那里,你在这里遇到的问题Edge是一个数据构造函数,其中一个字段包含一个对象,而Haskell中的相同语法是定义访问数据中几个字段的函数.

Haskell没有像PureScript那样的对象/记录作为第一类对象,所以你需要做的就是从你的对象中解包对象Edge:

show (Edge e) = "Edge from " ++ show e.from ++ " to " ++ show e.to