Tuesday, October 5, 2010

Learning a new (programming) language

I'm attempting to learn a new programming language. The main issue here is that F# isn't just a new language, it's a new type of language. There are three main (i.e. popular) paradigms of programming languages: imperative (the one you learn at school), object-orientated (the one most programmers use), and functional (the one I'm trying to learn). Object-orientated is really just an extension of imperative programming, so for me, learning F# is about learning how to re-think how to do things.

I thought I'd try to do the Euler problems like Andrew is doing at a misdirected effort.

My solution for problem 1 in F#:
let multiple x = if x % 3 = 0 || x % 5 = 0 then x else 0

let sequenceOfNumbers n = [1 .. n]

let euler1 numbers =
numbers
|> Seq.map multiple
|> Seq.sum

printf "Result = %i" (euler1 (sequenceOfNumbers 999))
The way I'd do it in C#, however, is:
static int Euler1(int maxValue)
{
var sum = 0;
for (var i = 1; i <= maxValue; i++
if
(i % 3 == 0 || i % 5 == 0)
sum += i;

return sum;
}
Is there really all that much difference? Could I have expressed it in F# in a more functional way? I don't know. Hopefully I can change the way I think about functional programming as I move through the problems.

No comments:

Post a Comment