Skip to content
gdm9000 edited this page Jun 12, 2017 · 26 revisions

F#, introduced in 2005, is Microsoft's version of OCaml for .NET. Which means that it's a functional language that supports OOP and the .NET framework, among other things. So, without learning anything about F#, let's see how compatible F# is with OCaml. Let's see if it execute this OCaml version of Euler1 a commenter sent me:

(* Euler1 in F# *)

let euler x =
    let rec aux i n =
        if i = 0 then n else
            aux (i-1)  (if i % 3 = 0 || i % 5 = 0 then n + i else n)
    in aux x 0

printfn "%i" (euler 999)

Well, the F# team has a handy-dandy web client that will let you try F# without installing anything - let's try that. Crossing my fingers, I pasted my code into the window and clicked Run. Wouldn't you know it - it worked! I got the following output:

233168
val euler : int -> int

That was too easy! How about the OCaml version that I wrote - the one based on my Haskell code with the weird 998 iterator size? Can anyone please tell me why this version needs to operate on 998?

(* Euler1 in F# *)

let rec range i j = i :: if i>j then [] else (range (i+1) j);;
let sum xs = List.fold (+) 0 xs;;

let myTest = fun x -> if x % 3 = 0 || x % 5 = 0 then true else false;;

let euler n = sum (List.filter myTest (range 0 n));;

Printf.printf "%d\n" (euler 998);;

Well, at first it threw errors, but after changing the names of the fold and mod functions, it worked! It produces a lot of gibberish along with the solution:

val range : int -> int -> int list
>
val sum : int list -> int
>
val myTest : int -> bool
>
val euler : int -> int
> 233168
val it : unit = ()
> >

So it appears that F# really is OCaml on .NET.

Clone this wiki locally