gpt4 book ai didi

PureScript 和类型类

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

我在使用 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

这给了我错误:
$ psc src/Attempt1.purs
Error at src/Attempt1.purs line 6, column 27:
Error in declaration showEdge
Cannot unify Prim.Object with Foo.Edge.

我猜这与它推断 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

我尝试的第二件事是:
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

这给了我:
$ psc src/Attempt2.purs
Error at src/Attempt2.purs line 5, column 1:
Type synonym instances are disallowed

所以我然后尝试明确列出基础类型:
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

这给了我:
$ 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.

我不知道“类型类实例头”是什么,所以我无处可去。

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

感谢您的帮助。

最佳答案

实际上,您第一次尝试就差不多了,您在这里遇到的问题是 Edge是一个数据构造函数,其中一个字段包含一个对象,而 Haskell 中的相同语法是定义用于访问数据中多个字段的函数。

Haskell 没有像 PureScript 那样将对象/记录作为第一类对象,因此您需要做的就是从 Edge 中解开对象。 :
show (Edge e) = "Edge from " ++ show e.from ++ " to " ++ show e.to

关于PureScript 和类型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26403392/

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