具有可变数量参数的OCaml函数 [英] OCaml function with variable number of arguments

查看:116
本文介绍了具有可变数量参数的OCaml函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如,一个a函数如下:

  let sum x1,x2,x3,.....,xn = x1 + x2,+ x3。 ... + xn 


解决方案

,肯定:

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

和(ab)的用法:

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

整洁,是吧?但不要使用它 - 这是一个黑客。



有关解释,请参阅此页(就SML而言,这个想法是一样的)。

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

解决方案

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

这篇关于具有可变数量参数的OCaml函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆