SoftTimur
SoftTimur

Reputation: 5490

Syntax of function declaration in OCaml

I would like to define a function as following:

let f (a: int) (b: int) (c: int) (d: int): int =
  ...

Is it possible to make the signature shorter without making them a tuple? As I still want f to have 4 arguments.

Thank you very much.

Edit1: I just think it is useless to repeat int 4 times, and image something like let f (a, b, c, d: int): int which actually is not allowed at the moment.

Upvotes: 9

Views: 8349

Answers (2)

Cristian Sanchez
Cristian Sanchez

Reputation: 32097

My OCaml is rusty but I believe you can do that by declaring your own type and by unpacking it in the function body.

type four = int*int*int*int

let myfunction (t:four) = 
   let a, b, c, d = t in 
      a + b + c + d;

You can also do this:

let sum4 ((a, b, c, d):int*int*int*int) = 
   a + b + c + d;;

Upvotes: 1

Pascal Cuoq
Pascal Cuoq

Reputation: 80255

Try this syntax:

let g: int -> int -> int -> int -> int =
  fun a b c d -> 
     assert false

It's not much shorter, but if you have a lot of these, you can define type arith4 = int -> int -> int -> int -> int and use that name as type annotation for g.

Upvotes: 13

Related Questions