Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

ocaml

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?

like image 451
Pramod Avatar asked Oct 28 '08 16:10

Pramod


People also ask

What is range function in Python?

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.

What is range called in Python?

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.

Is range only for integers Python?

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 .


1 Answers

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.

like image 139
Chris Conway Avatar answered Sep 19 '22 13:09

Chris Conway