Playing with F#

Posted by mroberts on Geeks with Blogs See other posts from Geeks with Blogs or by mroberts
Published on Thu, 25 Mar 2010 14:36:02 GMT Indexed on 2010/03/25 20:43 UTC
Read the original article Hit count: 313

Filed under:

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;
   3:   
   4:  namespace Problem001
   5:  {
   6:      class Program
   7:      {
   8:          static void Main(string[] args)
   9:          {
  10:              List<int> values = new List<int>();
  11:   
  12:              for (int i = 1; i < 1000; i++)
  13:              {
  14:                  if (i % 3 == 0 || i % 5 == 0)
  15:                      values.Add(i);
  16:              }
  17:              int total = 0;
  18:   
  19:              values.ForEach(v => total += v);
  20:   
  21:              Console.WriteLine(total);
  22:              Console.ReadKey();
  23:          }
  24:      }
  25:  }

 

Now, after much tweaking and learning, here is my solution in F#.

 

   1:  open System
   2:   
   3:  let calc n = 
   4:      [1..n]
   5:      |> List.map (fun x -> if (x % 3 = 0 || x % 5 = 0) then x else 0)
   6:      |> List.sum
   7:   
   8:  let main() = 
   9:      calc 999
  10:      |> printfn "result = %d"
  11:      Console.ReadKey(true) |> ignore 
  12:   
  13:  main()

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#.

© Geeks with Blogs or respective owner