[Haskell-cafe] Re : Defining Cg, HLSL style vectors in Haskell

minh thu noteed at gmail.com
Tue Nov 28 12:41:19 EST 2006

2006/11/28, Slavomir Kaslev <slavomir.kaslev at gmail.com>:
> Hello,
> I have to define a couple of float2, float3, float4 Cg, HLSL style
> vectors in Haskell. At first I was tempted to make them instances of
> Num, Floating, RealFrac, etc. but some of the functions defined in
> those classes have no sense for vectors. One such example is signum
> from class Num.
> There are several workarounds for this. One may come up with some
> meaning for vectors of such functions, for example:
> instance Num Float3 where
>     .....
>     signum a | a == Float3 0 0 0 = 0
>                   | otherwise = 1
> This is silly. Other option, which I prefer, is to leave such
> functions undefined (that is signum=undefined, not just not defining
> them). Is this ok? Are there any other options?
> Another bugging thing is that some of the functions do have meaning
> for vectors but they need different signatures. For example (**) ::
> Floating a => a -> a -> a, for vectors should be (**) :: (Floating a,
> Vector v) => v -> a -> v, that is (**) applied for every component of
> the vector. Any workarounds for that?
Those are the type signatures of +, ... you can't break them.
So it won't be possible to use + to add two values of different types.

> I know that I can scrap all those Num, Floating, RealFrac, etc.
> classes and define class Vector from scratch, but I really don't want
> to come up and use different names for +, -, etc. that will bloat the
> code.
> Last question: Does haskell have something like C++ templates? For
> example, some time in the future I may need types like int2, short3,
> etc., that behave just like float2, float3, but use different types
> for their components. I really, really wouldn't like to copy-paste the
> definitions of floatn and manually change their types to intn
> respectfully.
Yep, you have to learn that you can parametrise a type (constructor).
For exemple, realise that [1], ["hello"] and "hello" are values of different
types, i.e. different list types. The first one is of type [Int], the second one
is [String] and the third [Char] (so you see that String is simply [Char]).

In your case, you would want to define something like:
Data Float2 a = Float2 a a
then, optionnaly
type Float2Int = Fl2 Int

> Cheers.
> --
> Slavomir Kaslev
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe

More information about the Haskell-Cafe mailing list