Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCaml function with variable number of arguments

I'm exploring "advanced" uses of OCaml functions and I'm wondering how I can write a function with variable number of arguments.

For example, a function like:

let sum x1,x2,x3,.....,xn = x1+x2,+x3....+xn
like image 787
diegocstn Avatar asked Oct 20 '14 22:10

diegocstn


People also ask

Which variable contains the number of arguments?

The $# variable contains the number of arguments passed to a Bash script.

Can a function take unlimited number of arguments?

When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit. In the above function, if we pass any number of arguments, the result is always the same because it will take the first two parameters only.

What is Val in OCaml?

Well, val is a keyword in OCaml with several different uses. The cases you mention are both, in essence, that val is used in a module signature to specify values that appear in the module. Values are things like functions and expressions.


1 Answers

With a bit of type hackery, sure:

let sum f = f 0
let arg x acc g = g (acc + x)
let z a = a

And the (ab)usage:

# sum z;;
- : int = 0
# sum (arg 1) z;;
- : int = 1
# sum (arg 1) (arg 2) (arg 3) z;;
- : int = 6

Neat, huh? But don't use this - it's a hack.

For an explanation, see this page (in terms of SML, but the idea is the same).

like image 198
gsg Avatar answered Oct 10 '22 06:10

gsg