我在使用PureScript類型類時遇到了問題。我不得不說,我不是Haskell的專家,所以我很抱歉,如果這些都是明顯的錯誤。PureScript和類型類
我嘗試了幾種不同的方法,併爲每個方法打了一堵牆。我基本上試圖爲圖的邊界定義一個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。我一直無法弄清楚這一點。
感謝您的任何援助。