在 Haskell 中的 Num 实例中定义 fromInteger 函数
Define fromInteger function in Num instance on in Haskell
I tried to make it so that in the console the following
1 :: AlgebraicGraph Int
Will produce
Vertex 1
data AlgebraicGraph a
= Empty
| Vertex a
| Overlay (AlgebraicGraph a) (AlgebraicGraph a)
| Connect (AlgebraicGraph a) (AlgebraicGraph a)
instance Num a => Num (AlgebraicGraph a) where
fromInteger x = Vertex x
(+) x y = Overlay x y
(*) x y = Connect x y
But when I try fromInteger x = Vertex x, what I get is
Couldn't match type `a' with `Integer'
`a' is a rigid type variable bound by
the instance declaration
at AlgebraicGraph.hs:120:10-40
Expected type: AlgebraicGraph a
Actual type: AlgebraicGraph Integer
* In the expression: Vertex x
In an equation for `fromInteger': fromInteger x = Vertex x
In the instance declaration for `Num (AlgebraicGraph a)'
* Relevant bindings include
fromInteger :: Integer -> AlgebraicGraph a
Any help is much appreciated!
fromInteger x = Vertex x
问题是 x :: Integer
在那里,而不是 Num a => a
。改为这样做:
fromInteger x = Vertex (fromInteger x)
I tried to make it so that in the console the following
1 :: AlgebraicGraph Int
Will produce
Vertex 1
data AlgebraicGraph a
= Empty
| Vertex a
| Overlay (AlgebraicGraph a) (AlgebraicGraph a)
| Connect (AlgebraicGraph a) (AlgebraicGraph a)
instance Num a => Num (AlgebraicGraph a) where
fromInteger x = Vertex x
(+) x y = Overlay x y
(*) x y = Connect x y
But when I try fromInteger x = Vertex x, what I get is
Couldn't match type `a' with `Integer'
`a' is a rigid type variable bound by
the instance declaration
at AlgebraicGraph.hs:120:10-40
Expected type: AlgebraicGraph a
Actual type: AlgebraicGraph Integer
* In the expression: Vertex x
In an equation for `fromInteger': fromInteger x = Vertex x
In the instance declaration for `Num (AlgebraicGraph a)'
* Relevant bindings include
fromInteger :: Integer -> AlgebraicGraph a
Any help is much appreciated!
fromInteger x = Vertex x
问题是 x :: Integer
在那里,而不是 Num a => a
。改为这样做:
fromInteger x = Vertex (fromInteger x)