[Haskell-cafe] How to define an operation in terms of itself (but
of different type)?
Olex P
hoknamahn at gmail.com
Sat Jan 24 15:51:15 EST 2009
Cool! Thanks Ryan!
On Sat, Jan 24, 2009 at 8:31 PM, Ryan Ingram <ryani.spam at gmail.com> wrote:
> 2009/1/24 Olex P <hoknamahn at gmail.com>:
> > What I want to ask you guys can we define a function with arbitrary
> number
> > of parameters? Actually not really arbitrary but just several
> possibilities
> > (as we have with value constructors).
> > For instance cross product can have 1, 2 or 3 vectors as inputs depends
> on
> > the dimension. Is it 2d, 3d or 4d case.
>
> You need type classes plus some language extension to do this
> properly. Here's an example using type families:
>
> class Vector v => Cross v where
> type CrossResult v
> cross :: v -> CrossResult v
>
> instance Cross Vector2 where
> type CrossResult v = Vector2
> cross (Vector2 x y) = Vector2 (-y) x -- is this the right operation?
>
> instance Cross Vector3 where
> type CrossResult v = Vector3 -> Vector3
> cross (Vector3 x1 y1 z1) (Vector3 x2 y2 z2) = Vector3 (y1*z2 -
> z1*y2) (z1*x2 - x1*z2) (x1*y2 - y1*x2)
>
> etc.
>
> A difficult exercise is to define these operations in terms of each
> other inductively so that it works for arbitrary vector types; you
> need vectors indexed on some type-level natural, plus a bunch of
> hackery in the instances to make it work.
>
> -- ryan
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090124/ab9a8f01/attachment.htm
More information about the Haskell-Cafe
mailing list