Simplify List.walk (e.g. for dev backend)

This commit is contained in:
Richard Feldman 2023-08-15 02:15:56 -04:00
parent 6c8b1963ae
commit bac445b39b
No known key found for this signature in database
GPG Key ID: F1F21AA5B1D9E43B

View File

@ -459,9 +459,18 @@ contains = \list, needle ->
## Note that in other languages, `walk` is sometimes called `reduce`,
## `fold`, `foldLeft`, or `foldl`.
walk : List elem, state, (state, elem -> state) -> state
walk = \list, state, func ->
walkHelp : _, _ -> [Continue _, Break []]
walkHelp = \currentState, element -> Continue (func currentState element)
walk = \list, init, func ->
walkHelp list init func 0 (List.len list)
## internal helper
walkHelp : List elem, s, (s, elem -> s), Nat, Nat -> s
walkHelp = \list, state, f, index, length ->
if index < length then
nextState = f state (List.getUnsafe list index)
walkHelp list nextState f (Num.addWrap index 1) length
else
state
when List.iterate list state walkHelp is
Continue newState -> newState