Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

fromInteger x = Vertex x

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

fromInteger x = Vertex (fromInteger x)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading