What is the OCaml idiom equivalent to Python's range function? What is the OCaml idiom equivalent to Python's range function? python python

What is the OCaml idiom equivalent to Python's range function?


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]

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.


With Batteries Included, you can write

let nums = List.of_enum (1--10);;

The -- operator generates an enumeration from the first value to the second. The --^ operator is similar, but enumerates a half-open interval (1--^10 will enumerate from 1 through 9).


Here you go:

let rec range i j = if i > j then [] else i :: (range (i+1) j)

Note that this is not tail-recursive. Modern Python versions even have a lazy range.