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).
What is the right OCaml idiom for this?
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).
What is the right OCaml idiom for this?
Here you go:
let rec range i j = if i > j then [] else i :: (range (i+1) j)
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.
BTW, in Haskell you'd rather use
enumFromTo 1 n
[1 .. n]
These are just unnecessary.
take n [1 ..]
take n $ iterate (+1) 1
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).