12
\$\begingroup\$

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.

asked Sep 10, 2014 at 17:54
\$\endgroup\$
0

6 Answers 6

4
\$\begingroup\$

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
answered Sep 28, 2015 at 23:40
\$\endgroup\$
3
\$\begingroup\$

Never use begin [...] end

This:

begin [...] end 

is always synonymous with this:

([...])
Zach Gates
6,68831 silver badges75 bronze badges
answered Sep 28, 2015 at 23:56
\$\endgroup\$
2
\$\begingroup\$

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

answered Sep 29, 2015 at 13:18
\$\endgroup\$
2
\$\begingroup\$

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

answered Sep 29, 2015 at 13:35
\$\endgroup\$
1
\$\begingroup\$

downto

If you're not sure how to loop downwards, downto is usually the one to go for. Instead of:

for i=0 to 1000 do
Printf.printf"%d
"(1000-i)
done

You can do:

for i=1000 downto 0 do
Printf.printf"%d
"i
done
answered Jan 7, 2023 at 11:11
\$\endgroup\$
1
  • \$\begingroup\$ you could also do something like for i= -1000 to 0. Also, your syntax for these programs is missing the do done parts \$\endgroup\$ Commented Jan 17, 2023 at 22:23
0
\$\begingroup\$

print_string

Instead of the usual Printf.printf"", you can actually use the below (ONLY for strings, no formatting):

print_string"wassup"

Which is 1 byte shorter than:

Printf.printf"wassup"
answered Jan 7, 2023 at 11:06
\$\endgroup\$
1
  • \$\begingroup\$ Is this really worth a tip? It isn't normal to use Printf.printf for raw strings anyway \$\endgroup\$ Commented Jan 18, 2023 at 3:28

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.