Search code examples
ocaml

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


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?


Solution

  • 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.