aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorLouis Pilfold <louis@lpil.uk>2020-07-14 21:21:44 +0100
committerLouis Pilfold <louis@lpil.uk>2020-07-14 21:21:44 +0100
commit48d458d4f5785607fa236fd70e8dd773ab014699 (patch)
tree9c0e4fcd0b454fa010b81c668cb3db240b36160c /src
parent0cff914b427e2d37a3b889e0f9586ab59cef3d39 (diff)
downloadgleam_stdlib-48d458d4f5785607fa236fd70e8dd773ab014699.tar.gz
gleam_stdlib-48d458d4f5785607fa236fd70e8dd773ab014699.zip
list.key_set
Diffstat (limited to 'src')
-rw-r--r--src/gleam/list.gleam27
1 files changed, 26 insertions, 1 deletions
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam
index b13575b..06e5a33 100644
--- a/src/gleam/list.gleam
+++ b/src/gleam/list.gleam
@@ -954,7 +954,10 @@ pub fn pop_map(
/// > key_pop([tuple("a", 0), tuple("b", 1)], "c")
/// Error(Nil)
///
-pub fn key_pop(haystack, key) {
+pub fn key_pop(
+ haystack: List(tuple(k, v)),
+ key: k,
+) -> Result(tuple(v, List(tuple(k, v))), Nil) {
pop_map(
haystack,
fn(entry) {
@@ -966,3 +969,25 @@ pub fn key_pop(haystack, key) {
},
)
}
+
+/// Given a list of 2 element tuples, insert a key and value into the list.
+///
+/// If there was already a tuple with the key then it is replaced, otherwise it
+/// is added to the end of the list.
+///
+///
+/// ## Examples
+///
+/// > key_set([tuple(5, 0), tuple(4, 1)], 4, 100)
+/// [tuple(5, 0), tuple(4, 100)]
+///
+/// > key_set([tuple(5, 0), tuple(4, 1)], 1, 100)
+/// [tuple(5, 0), tuple(4, 1), tuple(1, 100)]
+///
+pub fn key_set(list: List(tuple(a, b)), key: a, value: b) -> List(tuple(a, b)) {
+ case list {
+ [] -> [tuple(key, value)]
+ [tuple(k, _), ..rest] if k == key -> [tuple(key, value), ..rest]
+ [first, ..rest] -> [first, ..key_set(rest, key, value)]
+ }
+}