简体   繁体   中英

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

OCaml is strongly typed, and many techniques used in other (untyped) languages are inapplicable. In my opinion (after 50 years of programming) this is a very good thing, not a problem.

The clearest way to handle a variable number of arguments of the same type is to pass a list:

# let sum l = List.fold_left (+) 0 l;;
val sum : int list -> int = <fun>
# sum [1;2;3;4;5;6];;
- : int = 21

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM