Project Euler is a awesome site. When working with a new language it can be tricky to find problems that need solving, that are more complex than "Hello World" and simpler than a full blown application. Project Euler gives use just that, cool and thought provoking problems that usually don't take days to solve.
I've solved a number of questions with C# and some with Java. BTW, I used Java because it had BigInteger support before .Net.
A couple weeks ago, back when winter had a firm grip on Columbus, OH, I began playing (researching) with F#. I began with Problem #1 from Project Euler. I started by looking at my solution in C#.
Here is my solution in C#.
1: using System;
2: using System.Collections.Generic;
4: namespace Problem001
6: class Program
8: static void Main(string args)
10: List<int> values = new List<int>();
12: for (int i = 1; i < 1000; i++)
14: if (i % 3 == 0 || i % 5 == 0)
17: int total = 0;
19: values.ForEach(v => total += v);
Now, after much tweaking and learning, here is my solution in F#.
1: open System
3: let calc n =
5: |> List.map (fun x -> if (x % 3 = 0 || x % 5 = 0) then x else 0)
6: |> List.sum
8: let main() =
9: calc 999
10: |> printfn "result = %d"
11: Console.ReadKey(true) |> ignore
Just this little example highlights some cool things about F#.
- Type inference. F# infers the type of a value. In the C# code above we declare a number of variables, the list, and a couple ints. F# does not require this, it infers the calc (a function) accepts a int and returns a int.
- Great built in functionality for Lists. List.map for example.
BTW, I don’t think I’m spilling the beans by giving away the code for Problem 1. It by far is the easiest question, IMHO, solved by 92,000+ people.
Next I’ll look into writing a class library with F#.