Haskell, Vectors and Simple Mechanics – part 1.

I like vectors! A long time ago my maths teacher introduced me to them and I just like the way three numbers (typically three) can express the notion of a position in space and combining these under different operations can produce other interesting properties.

Just recently I found this paper Learn Physics by Programming in Haskell which gives a very interesting Haskell oriented discussion on vectors and their use in mechanical problems. Reading it has inspired me to create my own implementation of vectors, bore you all senseless with it and see where it goes. What I’d like to do is:

  • Create a module for Vectors. How far this will go I’m not sure yet but it will most likely be over several posts and might get as far as vector calculus. I’ll also try to look at Monoids, Monads etc. from a vector perspective and indeed see if there are meaningful vector oriented implementations of these classes. I don’t know yet. Almost all my Haskell posts are learning experiences for me!
  • Apply the vector module to simple mechanical and geometric problems.
  • Create some sort of visualisation of the solutions to these problems. Here the Haskell Gloss package is a prime contender.
  • And it would be instructive to use QuickCheck too!

All nice and open ended and I’m writing the code more or less as I write the blog, so a lot may change! The code is in Github.

So here’s my first pass at a vector module.

The Vector itself is defined as a Haskell newtype. Internally the Vector has a three-tuple of Double (with type synonym Scalar). I went for a three-tuple rather than a list as all our vectors will be at most three dimensional and a tuple seemed a good fit. Maybe a list would be ‘better’ as it might simplify slightly the high-level functions mapVec, sumVec and zipWithVec that I’ve defined. The purpose of mapVec, sumVec and zipWithVec is to allow quite simple derivations of vector operations for addition, multiplication etc. along with the dot and cross product. (Having said all that I prefer the notation (x, y, z) to [x, y, z] as it looks more like how it would be written!)
Note also that there’s a number of custom operators, e.g. ‘^+^’, these allow us to write a ^+^ b rather than vAdd a b or a `vAdd` b

We can load this into ghci and try a few examples…
Here we just declare a vector a with components (1,2,3)

The magnitude and negation (reversal) of vector a.

This shows subtraction of vectors and the cross product.

The dot product and its type.

In part two we will look at rendering Vectors to the screen to help visualise further work.

Thanks for reading!

Leave a Reply

Your email address will not be published. Required fields are marked *

ˆ Back To Top