Skip to content

Commit dbdece8

Browse files
committed
Stdlib: add List.map_last and List.iter_last
1 parent 97a9f9d commit dbdece8

File tree

2 files changed

+21
-10
lines changed

2 files changed

+21
-10
lines changed

compiler/lib/generate.ml

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -61,15 +61,6 @@ let list_group f g l =
6161
| [] -> []
6262
| a :: r -> list_group_rec f g r (f a) [ g a ] []
6363

64-
(* like [List.map] except that it calls the function with
65-
an additional argument to indicate whether we're mapping
66-
over the last element of the list *)
67-
let rec map_last f l =
68-
match l with
69-
| [] -> assert false
70-
| [ x ] -> [ f true x ]
71-
| x :: xs -> f false x :: map_last f xs
72-
7364
(****)
7465

7566
type application_description =
@@ -1816,7 +1807,7 @@ and compile_decision_tree st loop_stack backs frontier interm loc cx dtree =
18161807
let l =
18171808
List.flatten
18181809
(List.map l ~f:(fun (ints, br) ->
1819-
map_last (fun last i -> int i, if last then br else []) ints))
1810+
List.map_last ~f:(fun last i -> int i, if last then br else []) ints))
18201811
in
18211812
!all_never, [ J.Switch_statement (cx, l, Some last, []), loc ]
18221813
in

compiler/lib/stdlib.ml

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,26 @@ module List = struct
271271
| x :: xs -> aux (x :: acc) xs
272272
in
273273
aux [] xs
274+
275+
(* like [List.map] except that it calls the function with
276+
an additional argument to indicate whether we're mapping
277+
over the last element of the list *)
278+
let rec map_last ~f l =
279+
match l with
280+
| [] -> assert false
281+
| [ x ] -> [ f true x ]
282+
| x :: xs -> f false x :: map_last ~f xs
283+
284+
(* like [List.iter] except that it calls the function with
285+
an additional argument to indicate whether we're iterating
286+
over the last element of the list *)
287+
let rec iter_last ~f l =
288+
match l with
289+
| [] -> ()
290+
| [ a ] -> f true a
291+
| a :: l ->
292+
f false a;
293+
iter_last ~f l
274294
end
275295

276296
let ( @ ) = List.append

0 commit comments

Comments
 (0)