From e5797a892d191ba3c04cb6b20cc63fa6d1c2d278 Mon Sep 17 00:00:00 2001 From: Marcin Puc Date: Sun, 7 Mar 2021 21:46:10 +0100 Subject: Make list.take_while tail recursive --- src/gleam/list.gleam | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam index 570769d..e49334b 100644 --- a/src/gleam/list.gleam +++ b/src/gleam/list.gleam @@ -1241,6 +1241,21 @@ pub fn drop_while( } } +fn do_take_while( + list: List(a), + predicate: fn(a) -> Bool, + acc: List(a), +) -> List(a) { + case list { + [] -> acc + [head, ..tail] -> + case predicate(head) { + True -> do_take_while(tail, predicate, [head, ..acc]) + False -> acc + } + } +} + /// Takes the first elements in a given list for which the predicate funtion returns `True`. /// /// ## Examples @@ -1252,12 +1267,6 @@ pub fn take_while( in list: List(a), satisfying predicate: fn(a) -> Bool, ) -> List(a) { - case list { - [] -> [] - [x, ..xs] -> - case predicate(x) { - True -> [x, ..take_while(xs, predicate)] - False -> [] - } - } + do_take_while(list, predicate, []) + |> reverse } -- cgit v1.2.3