Skip to content

Commit ee03f5a

Browse files
bsnyder788lpil
authored andcommitted
optimize map:fold recursion
1 parent af07c09 commit ee03f5a

File tree

2 files changed

+16
-9
lines changed

2 files changed

+16
-9
lines changed

gen/src/map_dict.erl

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -75,12 +75,15 @@ update(Dict, Key, F) ->
7575
put(Dict, Key, F({error, not_found}))
7676
end.
7777

78-
fold(Dict, Acc, F) ->
79-
Kvs = to_list(Dict),
80-
case Kvs of
78+
do_fold(List, Acc, F) ->
79+
case List of
8180
[] ->
8281
Acc;
8382

84-
[{K, V} | _] ->
85-
fold(delete(Dict, K), F(K, V, Acc), F)
83+
[{K, V} | Tail] ->
84+
do_fold(Tail, F(K, V, Acc), F)
8685
end.
86+
87+
fold(Dict, Acc, F) ->
88+
Kvs = to_list(Dict),
89+
do_fold(Kvs, Acc, F).

src/map_dict.gleam

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -87,10 +87,14 @@ pub fn update(dict, key, f) {
8787
}
8888
}
8989

90-
pub fn fold(dict, acc, f) {
91-
let kvs = to_list(dict)
92-
case kvs {
90+
fn do_fold(list, acc, f) {
91+
case list {
9392
| [] -> acc
94-
| [{k, v} | _] -> fold(delete(dict, k), f(k, v, acc), f)
93+
| [{k, v} | tail] -> do_fold(tail, f(k, v, acc), f)
9594
}
9695
}
96+
97+
pub fn fold(dict, acc, f) {
98+
let kvs = to_list(dict)
99+
do_fold(kvs, acc, f)
100+
}

0 commit comments

Comments
 (0)