[Haskell-cafe] Generic data constructor in pattern?
Henning Thielemann
lemming at henning-thielemann.de
Tue Aug 21 11:53:46 EDT 2007
On Tue, 21 Aug 2007, Peter Verswyvelen wrote:
> Consider the following example code:
>
> data Vector = V Float Float
> data Matrix = M Vector Vector
>
> liftV1 f (V x y) = V (f x) (f y)
> liftV2 f (V x1 y1) (V x2 y2) = V (f x1 x2) (f y1 y2)
>
> liftM1 f (M x y) = M (f x) (f y)
> liftM2 f (M x1 y1) (M x2 y2) = M (f x1 x2) (f y1 y2)
>
> Both pairs of lift functions have almost identical implementations. Can I
> merge these somehow? I know data constructors are first class values and are
> not types, but if I want to merge these lift functions I have to write
> something like
Maybe you are happy with instances of Control.Applicative (GHC-6.6)
http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Applicative.html
(untested code follows)
data Vector a = Vector a a
instance Functor a where
fmap f (Vector x y) = Vector (f x) (f y)
instance Applicative
pure x = Vector x x
(Vector fx fy) <*> (Vector x y) = Vector (fx x) (fy y)
pure f <*> vx
pure f2 <*> vx <*> vy
However, I'm not convinced that your code becomes more readable or
flexible by this change.
More information about the Haskell-Cafe
mailing list