PureScript 型クラスに問題があります。前もって、私は Haskell の専門家でもないので、これらが明らかな誤りである場合は申し訳ありません。
私はいくつかの異なるアプローチを試しましたが、それぞれに壁にぶつかりました。show
基本的に、グラフのエッジの関数を定義しようとしています。1 つのアプローチは次のようになります。
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
私が試した2番目のことはこれでした:
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.
「型クラス インスタンス ヘッド」が何かわからないので、そこから先がありません。
3 回の試みはすべて失敗しました。おそらく、まったく異なる理由で。PureScript は初めてなので、何が問題なのかわかりません。私は、さまざまなData.*
タイプの例を見て、PureScript by Exampleを読んで、フォローしようとしています。私はこれを理解することができませんでした。
ご協力ありがとうございます。