OCaml惯用法等同于Python的range函数? [英] What is the OCaml idiom equivalent to Python's range function?

查看:88
本文介绍了OCaml惯用法等同于Python的range函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个从1到n的整数列表.我可以在Python中使用range(1,n + 1)进行此操作,而在Haskell中可以使用:take n(iterate(1+)1).

I want to create a list of integers from 1 to n. I can do this in Python using range(1, n+1), and in Haskell using: take n (iterate (1+) 1).

为此,正确的OCaml习语是什么?

What is the right OCaml idiom for this?

推荐答案

我不知道成语,但这是使用中缀运算符的自然定义:

There is no idiom that I know of, but here is a fairly natural definition using an infix operator:

# let (--) i j = 
    let rec aux n acc =
      if n < i then acc else aux (n-1) (n :: acc)
    in aux j [] ;;
val ( -- ) : int -> int -> int list = <fun>
# 1--2;;
- : int list = [1; 2]
# 1--5;;
- : int list = [1; 2; 3; 4; 5]
# 5--10;;
- : int list = [5; 6; 7; 8; 9; 10]

或者, comprehensions语法扩展(其语法[i .. j])可能会包含在OCaml的社区版本"的将来版本中,因此可能会变得惯用.不过,如果您是该语言的新手,我不建议您开始使用语法扩展.

Alternatively, the comprehensions syntax extension (which gives the syntax [i .. j] for the above) is likely to be included in a future release of the "community version" of OCaml, so that may become idiomatic. I don't recommend you start playing with syntax extensions if you are new to the language, though.

这篇关于OCaml惯用法等同于Python的range函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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