tags:

views:

791

answers:

4

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?

+3  A: 

Here you go:

let rec range i j = if i > j then [] else i :: (range (i+1) j)
Thedric Walker
Not quite -- Python range(1,3) returns [1,2] while your (range 1 3) returns [1;2;3]. Change > to >=.
Darius Bacon
+7  A: 

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.

Chris Conway
your link to the community ocaml should point to:http://forge.ocamlcore.org/projects/batteries/
Thelema
The `--` operator is implemented in Batteries Included, although it produces an enum rather than a list.
Michael E
+1  A: 

BTW, in Haskell you'd rather use

enumFromTo 1 n
[1 .. n]

These are just unnecessary.

take n [1 ..]
take n $ iterate (+1) 1
ephemient
Thanks, I didn't realize that.
Pramod
+1  A: 

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

Michael E
Not sure I like -- for that, is it possible to define a .. operator?
aneccodeal
@aneccodeal No. OCaml does not allow operators starting with '.' (although they may contain '.' after the first character). The allowed characters for operators are defined in OCaml's lexical documentation here: http://caml.inria.fr/pub/docs/manual-ocaml/lex.html
Michael E