base icon indicating copy to clipboard operation
base copied to clipboard

List.init violates evaluation order of standard library

Open mmottl opened this issue 9 months ago • 0 comments
trafficstars

The following code demonstrates inconsistent behavior between the List.init function in Base and the same function in the OCaml standard library due to an incorrect evaluation order of list elements:

open Printf
open Base

let () =
  printf "Stdlib:\n\n";
  let r = ref 0 in
  Stdlib.List.init 10 (fun _i -> Int.incr r; !r) |>
  List.iter ~f:(printf "%d\n")

let () =
  printf "\n\nJane Street:\n\n";
  let r = ref 0 in
  List.init 10 ~f:(fun _i -> Int.incr r; !r) |>
  List.iter ~f:(printf "%d\n")

Output:

Stdlib:

1
2
3
4
5
6
7
8
9
10


Jane Street:

10
9
8
7
6
5
4
3
2
1

Note that the standard library uses [@tail_mod_cons] to achieve tail recursion without having to reverse the list.

mmottl avatar Jan 30 '25 19:01 mmottl