Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: class and function overloading:

Tags:

haskell

I am quite new to Haskell. I am trying to overload a custom function 'myadd' for different containers. My understanding is that you have to do it through classes. This is what i tried:

class Addition a where
  myadd :: a -> a -> a

instance Addition Int where
  myadd a b = a + b

instance Addition Maybe where
  myadd (Just a) (Just b) = Just (a + b)

main = do
  let a = 3 :: Int
  let b = 4
  let c = myadd a b
  print c

  let d = (Just a)
  let e = (Just b)
  let f = myadd d e
  print f

But i get the following errors:

test.hs:7:19: error:
    ? Expecting one more argument to ‘Maybe’
      Expected a type, but ‘Maybe’ has kind ‘* -> *’
    ? In the first argument of ‘Addition’, namely ‘Maybe’
      In the instance declaration for ‘Addition Maybe’
like image 923
user3689034 Avatar asked Feb 28 '26 05:02

user3689034


1 Answers

Addition has kind * -> *, so the argument to Addition must be of kind *. Maybe has kind * -> *. You need to pass an additional type argument to Maybe so that it has kind *.

instance Addition (Maybe a)

The problem with this is that Maybe a is not an instance of Addition for arbitrary a, only for a which are already instances of Addition. You can specify the requirement that a is an instance of Addition like this:

instance Addition a => Addition (Maybe a)

Also your implementation should use myadd instead of +:

instance Addition a => Addition (Maybe a) where
   myadd (Just a) (Just b) = Just (myadd a b)
like image 134
Justin Raymond Avatar answered Mar 01 '26 18:03

Justin Raymond



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!