OCaml function with variable number of arguments

I am studying the "advanced" functions of OCaml, and I am wondering how I can write a function with a variable number of arguments.

For example, a function such as:

let sum x1,x2,x3,.....,xn = x1+x2,+x3....+xn 
+6
source share
2 answers

With a few hackers like, sure:

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

And using (ab):

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

Neatly, huh? But do not use it - it is a hack.

See this page for clarification (from an SML perspective, but the idea is the same).

+9
source

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

The easiest 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 
+9
source

Source: https://habr.com/ru/post/977004/


All Articles