Functional programming: F# ray tracer
I'm subscribed to a lot of blogs. I don't really read a lot of them, I mostly scroll through them and look for interesting news or subjects. Sometimes I find particularly nice posts, like a couple of weeks ago; Christer Ericsson blogged about functional programming. I've been curious about learning a functional language since then.
I try to do some recreational programming every other weekend when Jennie is working, to develop my skills and to recapture the fun. So when I was in need of a project for last weekend I had two alternatives; to port Moonlight to the iPhone, or; do something with a functional language. The first alternative (that of course was an idea born out of alcohol) seamed a bit to ambitious. So I settled for the second, and decided that "do something" meant "write a ray tracer".
Functional programming is a different beast from "ordinary" (imperative, procedural, object oriented) programming:
- Instead of storing values of computations in variables you often see nested function calls, pattern matching and pipelines. Storing values in objects is known as a 'side effect' in CS lingo, so is I/O. In functional programming you often try to avoid functions with side effects. A function that has no side effects is called a pure function. Those are easier to optimize and parallelize, something that is becoming increasingly important (as all of us know by now, I guess).
- Recursion is often used instead of loops, in fact, loops doesn't exist as you might know them. Recursion might sound ineffective and limiting (call stack overflows etc.), but a lot of common recursions are optimized away by the compiler.
-
Type declarations are often short, defined in a mathematical way and they can be recursive.
Defining a binary tree data type in F# is as easy as:
type Tree = | Leaf of int | Node of int * Tree * Tree
An instance of this tree is also easy to create:
let myTree = Node(3, Leaf(1), Node(2, Leaf(3), Leaf(4)))
Which describes the tree:
I decided to go with F# for my ray tracer, a functional language created by Microsoft and released as a technology preview. It is compiled into a .NET application, which means that you can reference and use all the classes in the .NET Framework. This of course isn't of much use to a ray tracer, the only classes I used were the System.Drawing.Bitmap and System.Drawing.Color classes to save the rendered image as a png.
Results so far:
Comments
No comments so far. You leave the first:
© 2008 Markus Johnsson