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?
Python range() Function The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.
The range() is an in-built function in Python. It returns a sequence of numbers starting from zero and increment by 1 by default and stops before the given number. It has three parameters, in which two are optional: start: It's an optional parameter used to define the starting point of the sequence.
The Python range() works only with integers. It doesn't support the float type, i.e., we cannot use floating-point/decimal value in any of its arguments. For example, If you use range() with float step argument, you will get a TypeError 'float' object cannot be interpreted as an integer .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With