Haskell - writing a set of vector routines.

Started by
6 comments, last by MDI 16 years, 11 months ago
I'm going to try and learn Haskell properly (I think by writing a raytracer), once my exams have finished (on Friday). I already know SML, so it shouldn't be that hard. However, thinking about how I'm going to implement vectors, I've come across a problem. Writing an arbitrary dimensional vector class in C++ is easy, as I can use a parameter to a template to denote the length, the compiler can then check I'm not multiplying different dimensional vectors at compile time. How exactly can this be done in Haskell? Isn't this a dependent type? Is there a standard way around this?
Advertisement
*bump*
I too recently started learning haskell in my spare time. I found it superior to Ocaml which in turn i felt surpassed SML. But all that is neither here nor there. Incidentally, I just decided to make a linear algebra class to learn haskell's classes and stuff.

Anyways, why not simply represent your vector as a list of floats?

type Vector = [Float](.) a b = sum [ x * y | (x,y) <- zip a b]Hugs> [3 ,4, 5] . [5,7,7]78Hugs> [2, 3] . [2 ,-1]1
Just noticed you specified you didnt want different dimensions mishmashing, so maybe this?
type Vector = [Float](.) a b 	| length a /= length b = error "Type mismatch"	| otherwise = sum [ x * y | (x,y) <- zip a b]Hugs> [2, 3] . [2 ,-1,7]Program error: Type mismatchHugs> [2, 3] . [2 ,7]25
Someone more experienced may have better suggestions.
I'm not very experienced in Haskell, but I think using type classes might help a little. You define separate Vector2D, Vector3D, etc. types manually, and have them be instances of a general Vector type class. That way, you at least won't be able to combine Vector2Ds with Vector3Ds and such but still have polymorphic functions.

Automising the definition of the different VectorND classes... I don't think that's possible in plain Haskell. Maybe using Template Haskell?
Quote:Original post by MDI
How exactly can this be done in Haskell? Isn't this a dependent type? Is there a standard way around this?
It can be done without dependent types - you just have to encode the lengths in types instead of terms. See this and this.
compile time as well huh? I knew it wouldnt be that simple. well all that is beyond me, lucky rebooted is here =).
Ah, thanks for the suggestions guys!

This topic is closed to new replies.

Advertisement