Haskell - writing a set of vector routines.

This topic is 4226 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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?

*bump*

Share on other sites
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

Share on other sites
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.

Share on other sites
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?

Share on other sites
Quote:
 Original post by MDIHow 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.

Share on other sites
compile time as well huh? I knew it wouldnt be that simple. well all that is beyond me, lucky rebooted is here =).

Share on other sites
Ah, thanks for the suggestions guys!

1. 1
2. 2
3. 3
Rutin
15
4. 4
khawk
13
5. 5
frob
12

• 9
• 11
• 11
• 23
• 12
• Forum Statistics

• Total Topics
633663
• Total Posts
3013232
×