Home > Back-end >  Define fromInteger function in Num instance on in Haskell
Define fromInteger function in Num instance on in Haskell

Time:05-10

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!

CodePudding user response:

fromInteger x = Vertex x

The problem is that x :: Integer there, not Num a => a. Do this instead:

fromInteger x = Vertex (fromInteger x)
  • Related