diff options
author | Louis Pilfold <louis@lpil.uk> | 2023-10-02 22:23:51 +0100 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2023-10-02 22:23:51 +0100 |
commit | 081a4d9c417a971e00d7f0ea6706206d770d4733 (patch) | |
tree | bb602ac2f2b4cc2c341a5b7a57fbc5748137262c /src | |
parent | eda52ed9eee0b51efc4e3b70cdd77c60fd80447a (diff) | |
download | gleam_stdlib-081a4d9c417a971e00d7f0ea6706206d770d4733.tar.gz gleam_stdlib-081a4d9c417a971e00d7f0ea6706206d770d4733.zip |
list.key_filter
Diffstat (limited to 'src')
-rw-r--r-- | src/gleam/list.gleam | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam index 6be2f61..52e98ff 100644 --- a/src/gleam/list.gleam +++ b/src/gleam/list.gleam @@ -1448,6 +1448,40 @@ pub fn key_find( ) } +/// Given a list of 2-element tuples, finds all tuples that have a given +/// key as the first element and returns the second element. +/// +/// This function may be useful for interacting with Erlang code where lists of +/// tuples are common. +/// +/// ## Examples +/// +/// ```gleam +/// > key_filter([#("a", 0), #("b", 1), #("a", 2)], "a") +/// [0, 2] +/// ``` +/// +/// ```gleam +/// > key_filter([#("a", 0), #("b", 1)], "c") +/// [] +/// ``` +/// +pub fn key_filter( + in keyword_list: List(#(k, v)), + find desired_key: k, +) -> List(v) { + filter_map( + keyword_list, + fn(keyword) { + let #(key, value) = keyword + case key == desired_key { + True -> Ok(value) + False -> Error(Nil) + } + }, + ) +} + fn do_pop(haystack, predicate, checked) { case haystack { [] -> Error(Nil) |