Haskell newtype but keep the old functions

I want to define the type "Ideal", which is a list, but with some structure. The numerical prelude already defines Ring instances for lists, but they don't use the addition and multiplication definitions I want. So I think in this case I have to say

 newtype Ideal a = Ideal [a] 

This works fine, but now it gives me an error if I try to do, say take 5 $ Ideal [0..] .

Is there a way to save the functions that I want and only override the definitions that I explicitly override?

+8
haskell
source share
2 answers

If you are not too tuned that everything is completely automatic, you can use utility functions in the newtype package , for example. something like over Ideal $ take 5 .

Edit: Also, aside, it is not too difficult to extend the functions from the newtype package to handle other cases. For example, I had the following definitions:

 infixl 3 ./ (./) :: (Newtype no) => (o -> t) -> (n -> t) (./) fx = fx . unpack liftN fx = pack $ f ./ x liftN2 fxy = pack $ f ./ x ./ y liftN3 fxyz = pack $ f ./ x ./ y ./ z 

Actually not the best design for such combinators, I suspect, but you get the point.

+11
source share

For simple functions, no. You will need to provide your own definitions.

However, for functions belonging to a type class, you can use the GeneralizedNewtypeDeriving extension to derive type classes from the desired newtype type.

 {-# LANGUAGE GeneralizedNewtypeDeriving #-} newtype MyState a = MyState (State Int a) deriving (Monad) 
+6
source share

All Articles