Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax of function declaration in OCaml

Tags:

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.

like image 322
SoftTimur Avatar asked Jul 23 '11 16:07

SoftTimur


People also ask

How do you declare a function in syntax?

Declaring a function - function prototypestype functionName( type [argname] [, type, ...] ); Example: // declare a function prototype for the add function, taking two integer // arguments and returning their sum int add (int lhs, int rhs);

How do you define a function in OCaml?

Using Operator as Function They can be used as a function in ocaml. A function call has the form f arg1 arg2 with function named f , while operator such as + is used in the form arg1 + arg2 .

How do you declare a variable in OCaml?

At its simplest, a variable is an identifier whose meaning is bound to a particular value. In OCaml these bindings are often introduced using the let keyword. We can type a so-called top-level let binding with the following syntax. Note that variable names must start with a lowercase letter or an underscore.

What does -> mean in OCaml?

The way -> is defined, a function always takes one argument and returns only one element. A function with multiple parameters can be translated into a sequence of unary functions.


2 Answers

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.

like image 90
Pascal Cuoq Avatar answered Oct 14 '22 01:10

Pascal Cuoq


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;;
like image 22
Cristian Sanchez Avatar answered Oct 14 '22 03:10

Cristian Sanchez