Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use fromInteger with no implicit prelude in Haskell?

Tags:

haskell

ghc

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.

like image 650
Marc Avatar asked Oct 19 '10 14:10

Marc


People also ask

What is Prelude haskell?

From HaskellWiki. Prelude is a module that contains a small set of standard definitions and is included automatically into all Haskell modules.


1 Answers

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
like image 57
sepp2k Avatar answered Nov 15 '22 23:11

sepp2k