OCaml - gregorymorrison/euler1 GitHub Wiki

OCaml is an object-oriented, statically typed, functional language which debuted in 1996. Here is Euler1 in OCaml. This code is obviously of the formula-oriented variety like Haskell. Note, for instance, that there are no mutable variables here - simply formulas for range(), sum(), myTest(), and euler(), which is a composition. Ocaml isn't strict about immutability - it just discourages it:

#!/usr/bin/ocaml
(* Euler1 in OCaml *)

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

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

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

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

My version of Euler1 is probably not the most compact or idiomatic; I've only spent a few hours with this language. I imagine there are built-in facilities I could have used to shorten my code. Inspired no doubt by Python, the OCaml community is making an effort to create a distribution with all kinds of bells and whistles - Batteries Included, which I'm sure would have shortened my code.

It took me ~3 or 4 hours to write this - not that bad. One thing that stumps me - why does euler(998) work instead of euler(999)? Someone please solve this for me!

To get OCaml on Fedora, simply yum install ocaml. OCaml has a few ways to execute your code. Its compiler has an option to bundle an OCaml runtime with your code for distribution - nice! Here I simply execute my program as a script:

$ ./euler1.ocml
233168