0

I have some typeclass C with a function that is supposed to give me the next bigger number, if there is one.

That means for integral types it just does +1, for types that represent a superset of the whole numbers it is supposed to return Nothing because there is no definite next number.

{-# LANGUAGE FlexibleInstances, UndecidableInstances #-} 
module Main where

class C a where
    cIncr :: a -> Maybe a

instance Integral a => C a where
    cIncr x = Just $ x + 1

instance Fractional a => C a where
    cIncr _ = Nothing

This gives me following error:

Duplicate instance declarations:
  instance Integral a => C a
    -- Defined at src/File.hs:7
  instance Fractional a => C a
    -- Defined at src/File.hs:10

I don't understand why I get this error - why/where do they define the same instances?

snøreven
  • 1,904
  • 2
  • 19
  • 39
  • 1
    Also relevant: [*Haskell: Overlapping instances*](http://stackoverflow.com/q/1064232/2751851), and [this answer to *How do I write, “if typeclass a, then a is also an instance of b by this definition.”*](http://stackoverflow.com/a/3216937/2751851). By the way, I'm not sure there would be much to gain by having `cIncr` for e.g. `Double` returning always `Nothing` (if you got your instance to work), rather than simply leading to a type error (if you removed the instance). – duplode Apr 29 '17 at 15:49
  • @duplode: Thanks, I'll read that. I need to know if there is a next value (and what it is) for the type used and handle some things differently if there is not. That's why I need instances for all integral numbers and ones for all non-integral numbers. The `Nothing` is used - it's not some kind of error. – snøreven Apr 29 '17 at 15:57
  • 1
    Note that, if you are okay with giving up on deciding solely on the basis of which instances happen to exist, there is the option of introducing a wrapper type with two constructors that encoding the difference, while using GADTs or plain old "smart constructors" (cf. options 2 and 4 in [this answer](http://stackoverflow.com/a/19650352/2751851) to ensure only sensible values can be constructed. – duplode Apr 29 '17 at 16:59

0 Answers0