OCaml, a first glance at functional programming

First impression with Ocaml : powerful, elegant when you know what you are writing about, and bizarre. But that’s opens up a new experience.

let rec concat =
  fun l1 ->
  fun l2 ->
  match (l1, l2) with
    (t1::r1, l) -> t1::(concat r1 l)
    | (l, []) -> l
    | ([], l) -> l;;

let rec map =
  fun f ->
  fun l ->
  match (l) with
    | (t::r) -> (f t)::(map f r)
    | [] -> [];;

let rec partition =
  fun l ->
  match l with
    | (t::r) -> concat (map (fun x -> t::x) (partition r) ) (partition r)
    | (t) -> [t];;

And this gives you all possible partitions of an ensemble.
Like:

# partition [3;4;5];;
- : int list list = [[3; 4; 5]; [3; 4]; [3; 5]; [3]; [4; 5]; [4]; [5]; []]
Advertisements

3 thoughts on “OCaml, a first glance at functional programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s