Xilexio
Xilexio

Reputation: 1238

Polymorphic variable used in different contexts haskell

I have a following piece of Haskell code:

foo :: Num a => (a -> a) -> Either Integer Double -> Either Integer Double
foo f x = case x of
  Left i -> Left $ f i
  Right d -> Right $ f d

It doesn't compile with error "Couldn't match type Integer with Double". I understand that type of f is computed as Integer -> Integer and Double -> Double in Left and Right expressions respectively, creating a collision.

How can I change this function, so that correct version of f would be used each time?

Upvotes: 4

Views: 86

Answers (1)

YellPika
YellPika

Reputation: 2902

You need RankNTypes.

{-# LANGUAGE RankNTypes #-}

foo :: (forall a. Num a => a -> a) -> Either Integer Double -> Either Integer Double
foo f x = case x of
    Left i -> Left $ f i
    Right d -> Right $ f d

Upvotes: 6

Related Questions