Skip to content

List.init violates evaluation order of standard library #175

@mmottl

Description

@mmottl

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    forwarded-to-js-devsThis report has been forwarded to Jane Street's internal review system.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions