haskellnewtypecoerce

Is there a shorthand for operations like `fromNewtype . f . toNewtype`?


A pattern that presents itself the more often the more type safety is being introduced via newtype is to project a value (or several values) to a newtype wrapper, do some operations, and then retract the projection. An ubiquitous example is that of Sum and Product monoids:

λ x + y = getSum $ Sum x `mappend` Sum y
λ 1 + 2
3

I imagine a collection of functions like withSum, withSum2, and so on, may be automagically rolled out for each newtype. Or maybe a parametrized Identity may be created, for use with ApplicativeDo. Or maybe there are some other approaches that I could not think of.

I wonder if there is some prior art or theory around this.

P.S.   I am unhappy with coerce, for two reasons:


Solution

  • Your "spiked monster" example is better handled by putting the summands into a list and using the ala function available here, which has type:

    ala :: (Coercible a b, Coercible a' b') 
        => (a -> b) 
        -> ((a -> b) -> c -> b')   
        -> c 
        -> a' 
    

    where

    in your case, it would be something like:

    ala Sum foldMap [1,2::Integer]
    

    "ala" functions can be implemented through means other than coerce, for example using generics to handle the unwrapping, or even lenses.