Question

type PT_Int = Int
type PT_String = String
data PolyType = PT_Int Int | PT_String String

Given a function f, how do I write a function that lifts it into PolyType? (just trying to understand lifting)

Was it helpful?

Solution

Your PolyType is equivalent to Either Int String. In case you haven't seen Either before:

data Either a b = Left a | Right b

so you could have a function like

liftP :: (Either Int String -> a) -> PolyType -> a
liftP f poly = case poly of
    PT_Int    i -> f (Left i)
    PT_String s -> f (Right s)

PolyType contains either Int or String, so you can only lift functions that are defined over both Int and String.

That said, I don't think this is what you're after. The term "lifting" is usually used in the context of polymorphic data types like [a], Maybe a, (->) a or in general some type f a where f :: * -> *.

In these cases, given a function g :: a -> b, you want a new function [a] -> [b], Maybe a -> Maybe b or in general f a -> f b. This is exactly fmap from Functor.

class Functor f where
    fmap :: (a -> b) -> (f a -> f b)

but your PolyType is monomorphic (it doesn't have a free variable in its type. To be precise, it has kind *) so it can't be a Functor.

You chould change your definition of PolyType to

data PolyType a = PT a

Now this is a valid Functor (it's just the Identity Functor)

instance Functor PolyType where
    fmap f (PT a) = PT (f a)

The type of fmap (specialized for this particular PolyType instance) is

fmap :: (a -> b) -> PolyType a -> PolyType b
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top