Search this blog

02 February, 2008

Functional programming in c#

Functional programming is becoming more popurlar and mainstream. C# is embracing it, mostly due to the recent inclusion of the LINQ technology (a SQL-like language extension to manage queries on objects), but still, it's a more than welcome addition. As usual with Microsoft, C# started as a copy of an existing technology (Java), but now has been refined so much that not only has in my opinion surpassed its master, but is one of the most beautiful "mainstream" languages nowdays.

A few links (very intresting, but mostly unuseful):
A nice and self-contained reading about building data with closures.
Y combinator, in C#
Immutable data structures in C#

More immutability
LazyLoader class

LINQ raytracer


A few links (very intresting, with practical use):
C# 3 raytracer
Microsoft F#

Note that I've placed the "immutable data structures" links in the unuseful section. There is quite a bit of research in the C# community about immutability, mostly in order to ease parallel programming. I don't really like those kinds of approaches to the problem, when you drop an immutable data structure in an inpure world, you still have to lock every time you need to "publish" a "new version" of your data. Those locks are simple, they can be even implemented in a lockless way, but then multiple concurrent updates are a trouble and can easily cause livelocks for complex structures. And you have to lock on reads as well if you're not confortable with the idea of reading possibly "old" data, but if that is not a problem, then you could even stick with imperative data structures, and make copies of them, that buffering solution is the most used in games (between the two main threads, simulation and rendering)

Most impure functional languages work the other way, they encourage a programming style that is impure in the implementation details, but that as a whole, do not have side effects, so you can drop impure code into a purely functional world.
I would rather have immutable interfaces to mutable data structures, i.e. C++ deep constness, to be capable of not locking if I'm sure that all the threads are feeded with a readonly version of the data structure.

No comments: