Ocaml code for 2d vectors

December 11th, 2008

The convex layers of a point set, a data struc...Image via WikipediaFlying Frog consultancy has some great Ocaml tutorials. They also sell a book and access to Ocaml journal. When I made games in c++ I praised the fact that I used 2d vectors for all 2d stuff instead of separate x, y floats. This made code much shorter and I could do tons of simulation with basic vector operations (like acceleration’s, forces, collisions, rotations..).

One of the examples on FF Consultancy includes a very compact set of 2d vector functions and operators also. A great start to begin a dive at Ocaml game-dev experiment.

(* This is a comment (* mine *). Multiline comments can be nested. *)

(* We define a new type vec2. Vec2 is a record, one of OCaml's data structures *)
type vec2 = { x: float; y: float }

(* We define a constructor function for this type. { } is there because we are
    creating a record, they don't wrap a function like in c like languages *)
let vec2 x y = {x=x; y=y}

(* This is a function that creates the zero vector, it uses previously
    defined function vec2. *)
let zero = vec2 0. 0.

(* Surprisingly to some, OCaml doesn't have operator overloading
    These are operators over vec2, again { } are here because of record *)
let ( +| ) a b = {x = a.x +. b.x; y = a.y +. b.y}
let ( -| ) a b = {x = a.x -. b.x; y = a.y -. b.y}
let ( ~| ) a = {x = -. a.x; y = -. a.y}
let ( *| ) s r = {x = s *. r.x; y = s *. r.y}

(* And some basic functions for vectors. *)
let normal a = { x = a.y; y = -. a.x }
let dot a b = a.x *. b.x +. a.y *. b.y
let length2 r = dot r r
let length r = sqrt(length2 r)
let unitise r = 1. /. length r *| r

(* example: the distance between two points *)
let distance r t = length r -| t

You can see that OCaml code is very compact. OCaml has a strict static type system, but if you look at the code I declared just the 2 floats. This is because OCaml compiler figures out of what type something is!

Ocaml is known for it’s speed that comes close to c++, but it provides a much safer and higher level programming environment. OCaml is an unpure functional language which can also do imperative and object oriented programming.

It’s very interesting language, different in a lot of ways to your papa’s cup of java/python/perl/c++ . Mainly, because it’s a functional language !

I wrote more about OCaml in my previous posts. This post was basically one of the first ones I tried to write but didn’t finish it back then, so I am posting it now.

Reblog this post [with Zemanta]
Read and let read :)
  • del.icio.us
  • Reddit
  • Digg
  • DZone
  • email
  • Facebook
  • HackerNews
  • Twitter
  • StumbleUpon

Leave a Reply