Skip to content

Commit

Permalink
Add more tail-recursive List functions
Browse files Browse the repository at this point in the history
  • Loading branch information
alavrik committed Jun 28, 2015
1 parent 58a2488 commit 98cd2b5
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 17 deletions.
13 changes: 5 additions & 8 deletions piqilib/piqi.ml
Original file line number Diff line number Diff line change
Expand Up @@ -878,22 +878,19 @@ let parse_scoped_name name =
| _ -> assert false (* this has been checked already *)


(* replace the first list element for which [f] returns true with [x]
*
* NOTE: non-tail recursive
*)
(* replace the first list element for which [f] returns true with [x] *)
let list_replace l f x =
let rec aux = function
let rec aux accu = function
| [] ->
(* we were supposed to replace an item before we reached the end of the
* list *)
assert false
| h::t ->
if f h
then x::t
else h::(aux t)
then List.rev_append accu (x::t)
else aux (h::accu) t
in
aux l
aux [] l


let name_of_function x = x.T.Func.name
Expand Down
42 changes: 33 additions & 9 deletions piqilib/piqi_util.ml
Original file line number Diff line number Diff line change
Expand Up @@ -45,23 +45,47 @@ let rec list_count_append l1 l2 count =
let list_append l1 l2 = list_count_append l1 l2 0


let list_concat l =
let rec aux accu = function
| [] -> List.rev accu
| h::t -> aux (List.rev_append h accu) t
in
aux [] l


module Std =
struct
module List =
struct
include List

let map = Piqi_piqirun.list_map

let append = list_append
let concat = list_concat

let concat l =
let rec aux accu = function
| [] -> rev accu
| h::t -> aux (rev_append h accu) t
in
aux [] l

let flatten = concat

let fold_right f l accu =
fold_left (fun a b -> f b a) accu (rev l)

let split l =
let rec aux accu_a accu_b = function
| [] ->
rev accu_a, rev accu_b
| (a,b)::t ->
aux (a::accu_a) (b::accu_b) t
in
aux [] [] l

let combine l1 l2 =
let rec aux accu l1 l2 =
match l1, l2 with
| [], [] -> rev accu
| (h1::t1), (h2::t2) ->
aux ((h1, h2)::accu) t1 t2
| (_, _) ->
invalid_arg "List.combine"
in
aux [] l1 l2
end

let ( @ ) = List.append
Expand Down

0 comments on commit 98cd2b5

Please sign in to comment.