OCaml function with variable number of arguments

本秂侑毒 提交于 2019-12-06 02:13:59

问题


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

回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/26475765/ocaml-function-with-variable-number-of-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!