簡體   English   中英

PureScript和類型類

[英]PureScript and typeclasses

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

我猜這與它在show的定義中推斷e的類型這一事實有關。 我在這里嘗試添加類型注釋,但是我收到了語法錯誤:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM