11

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

2 Answers 2

19

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

Sign up to request clarification or add additional context in comments.

2 Comments

I wouldn't use this because passing an int list is the better way. But very nice use of higher level functions and continuation passing style.
BTW this is how the Printf module is implemented
10

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

2 Comments

"many techniques used in other (untyped) languages are inapplicable." Are you saying variadic functions aren't possible in strongly typed languages?
A list does not allow you to pass variables with different types. I.e.: on Clojure: user=> (defn greet [& arg] (str arg))

Your Answer

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.