From 081a4d9c417a971e00d7f0ea6706206d770d4733 Mon Sep 17 00:00:00 2001 From: Louis Pilfold Date: Mon, 2 Oct 2023 22:23:51 +0100 Subject: list.key_filter --- src/gleam/list.gleam | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) (limited to 'src') 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) -- cgit v1.2.3