[Haskell-cafe] Generic data constructor in pattern?
Peter Verswyvelen
bf3 at telenet.be
Tue Aug 21 11:07:47 EDT 2007
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
lift1 f (d x y) = d (f x) (f y)
lift2 f (d x1 y1) (d x2 y2) = d (f x1 x2) (f y1 y2)
But this does not work, as the pattern matcher does not seem to like this.
Thanks,
Peter Verswyvelen
PS: Of course I could define a single type like:
data Pair a = P a a
type Vector = Pair Float
type Matrix = Pair Vector
lift1 f (P x y) = P (f x) (f y)
lift2 f (P x1 y1) (P x2 y2) = P (f x1 x2) (f y1 y2)
But that's beside the question :)
More information about the Haskell-Cafe
mailing list