Local definitions in the class instances

Boris Lykah lykahb at gmail.com
Thu Jan 27 12:07:58 CET 2011


I think it would be convenient to allow adding variables and
functions, which are not members of the class,  to a class instance so
that they are visible only in the instance scope. It will help if the
same functions are used by several class functions.

Example:
When implementing Num class for my datatype, I found that I routinely
do unwrapping in each operator definition. I extracted it into
functions, but as they are used only in instance definition, I want to
put them there and restrict them to that scope. It would be neater
than leaving them in the global scope or copypasting into each
operator.

> newtype Wrapped = Wrapped Integer deriving (Show, Eq)

> instance Num Wrapped where
>   (+) = lift2 (+)
>   (-) = lift2 (-)
>   (*) = lift2 (*)
>   abs = lift abs
>   signum = lift signum
>   fromInteger = Wrapped
>   lift2 f (Wrapped a) (Wrapped b) = Wrapped (f a b)
>   lift f (Wrapped a) = Wrapped (f a)

The extension implementation should be very simple.

--
Regards,
Boris



More information about the Haskell-prime mailing list