tags:

views:

93

answers:

1

The following program yields an error in ghci:

{-# LANGUAGE NoImplicitPrelude #-}

import Prelude (Integer, Bool)
import qualified Prelude

class Discrete a where
    (==) :: a -> a -> Bool

instance Discrete Integer where
    (==) = (Prelude.==)

class Monoid a where
    one :: a
    (*) :: a -> a -> a

    fromInteger :: Integer -> a
    fromInteger 1 = one

Namely:

fromInteger.hs:17:16:
No instance for (Monoid Integer)
arising from the literal 1' at fromInteger.hs:17:16
Possible fix: add an instance declaration for (Monoid Integer)
In the pattern: 1
In the definition of
fromInteger': fromInteger 1 = one

How can I fix it so that 1 can be converted to the value one for Monoids? All other integers may (or should) yield Prelude.undefined when being applied to (Monoid a) => fromInteger.

Please be aware that I am a the opposite of an expert to Haskell so please forgive me in case the answer is obvious.

+5  A: 

The problem is that (with NoImplitPrelude) you can only use integer literals for types for which there is a fromInteger function in scope.

So in your code you can only use integer literals to represent instances of Monoid and since in your code, Integer is not an instance of Monoid, you can not use the literal 1 to represent the Integer 1.

To fix this you could create another module which does import the prelude and define integerOne :: Integer = 1.

You could then define your fromInteger function as:

fromInteger x | x == integerOne = one
sepp2k