Tips for golfing in OCaml

9

2

Inspired from the assortment of other 'Tips for golfing in language xyz'. As usual, please only suggest tips that are specific to OCaml and not programming in general. One tip per answer please.

icedvariables

Posted 2014-09-10T17:54:47.830

Reputation: 453

1Mind if I add a few obvious tips? – Édouard – 2015-09-28T23:39:43.977

Answers

3

Use functions instead of match

let rec f=function[]->0|_::t->1+f t

is shorter than

let rec f x=match x with[]->0|_::t->1+f t

Édouard

Posted 2014-09-10T17:54:47.830

Reputation: 205

2

Never use begin […] end

This:

begin […] end 

is always synonymous with this:

([…])

Édouard

Posted 2014-09-10T17:54:47.830

Reputation: 205

1

Define several variables or functions at once

Thanks to tuples, you can define several variables at once. And as functions are first-class citizens…:

let f,g=(fun x->x+1),fun x->2*x

You can’t, however, write:

let f,g=(fun x->x+1),fun x->2*f x

Error: Unbound value f

Unfortunately, you can’t avoid the issue by using rec:

let rec f,g=(fun x->x+1),fun x->2*f x

Error: Only variables are allowed as left-hand side of let rec

Édouard

Posted 2014-09-10T17:54:47.830

Reputation: 205

1

Exploit curryied functions

Functions in OCaml are curryied. It might be useful to exploit that fact sometimes.

let n y=f x y

can be written

let n=f x

If you need arithmetic operations, you can surround them with parentheses so they behave like standard, prefix functions. (+), (-), …

let n=(+)1;;
n 3;;

- : int = 4

Édouard

Posted 2014-09-10T17:54:47.830

Reputation: 205