Tag Archives: F#

Project Euler: Problem 1 (in F#)

I have already done Project Euler Problem 1 in C#. Since I am currently learning F#, I thought I’d give it another shot:

let rec sumMultiples(data) =
    match data with
    | [] -> 0
    | head::tail when (head % 3 = 0 || head % 5 = 0) -> head + sumMultiples(tail)
    | _::tail -> sumMultiples(tail)

It produces the correct result, but seeing as how LINQ considerably simplified the C# version, and since I am a complete F# and functional programming n00b, I suspected there must be a better way.

I hate it when I’m right.

This solution is better, in my opinion:

List.sum(List.filter (fun n -> n % 3 = 0 || n % 5 = 0) [1..999]);;

Anyhow, I know I have a lot left to learn, so I’m looking forward to exploring the functional side of programming in the coming months.

Update 2010-01-08: Ooh, better yet:

[1..999] |> List.filter (fun n -> n % 3 = 0 || n % 5 = 0) |> List.sum;;

Pipelining FTW!