From 557ae4dd9cefcbc95220494b22d138269d484e93 Mon Sep 17 00:00:00 2001 From: Brian Carroll Date: Mon, 4 Jul 2022 14:57:18 +0100 Subject: [PATCH] builtins: Implement List.mapWithIndex in pure Roc --- crates/compiler/builtins/roc/List.roc | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/compiler/builtins/roc/List.roc b/crates/compiler/builtins/roc/List.roc index 0732b392f9..1e07bb4094 100644 --- a/crates/compiler/builtins/roc/List.roc +++ b/crates/compiler/builtins/roc/List.roc @@ -570,6 +570,23 @@ map4 : List a, List b, List c, List d, (a, b, c, d -> e) -> List e ## This works like [List.map], except it also passes the index ## of the element to the conversion function. mapWithIndex : List a, (a, Nat -> b) -> List b +mapWithIndex = \src, func -> + length = len src + dest = withCapacity length + + mapWithIndexHelp src dest func 0 length + +# Internal helper +mapWithIndexHelp : List a, List b, (a, Nat -> b), Nat, Nat -> List b +mapWithIndexHelp = \src, dest, func, index, length -> + if index < length then + elem = getUnsafe src index + mappedElem = func elem index + newDest = append dest mappedElem + + mapWithIndexHelp src newDest func (index + 1) length + else + dest ## Returns a list of all the integers between one and another, ## including both of the given numbers.