aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorLouis Pilfold <louis@lpil.uk>2020-05-25 10:59:04 +0100
committerLouis Pilfold <louis@lpil.uk>2020-05-26 19:19:29 +0100
commite501f3d55661ba9ca748cc2d5b2e63a3db302e2e (patch)
tree5fa7a1c88d6b53a8313d10ea8cfa18e3e63c8738 /src
parent90eb83c27ffad8172b4b5d05435216c21741ea73 (diff)
downloadgleam_stdlib-e501f3d55661ba9ca748cc2d5b2e63a3db302e2e.tar.gz
gleam_stdlib-e501f3d55661ba9ca748cc2d5b2e63a3db302e2e.zip
set.from_list
Diffstat (limited to 'src')
-rw-r--r--src/gleam/list.gleam2
-rw-r--r--src/gleam/set.gleam24
2 files changed, 25 insertions, 1 deletions
diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam
index c0414d4..351d466 100644
--- a/src/gleam/list.gleam
+++ b/src/gleam/list.gleam
@@ -426,7 +426,7 @@ pub fn flatten(lists: List(List(a))) -> List(a) {
///
/// This function runs in linear time.
///
-pub fn fold(list: List(a), from initial: b, with fun: fn(a, b) -> b) -> b {
+pub fn fold(over list: List(a), from initial: b, with fun: fn(a, b) -> b) -> b {
case list {
[] -> initial
[x, ..rest] -> fold(rest, fun(x, initial), fun)
diff --git a/src/gleam/set.gleam b/src/gleam/set.gleam
index a654200..09e92a5 100644
--- a/src/gleam/set.gleam
+++ b/src/gleam/set.gleam
@@ -1,5 +1,6 @@
import gleam/map.{Map}
import gleam/result
+import gleam/list
/// A set is a collection of unique elements of the same type.
///
@@ -65,6 +66,8 @@ pub fn contains(in set: Set(element), this member: element) -> Bool {
/// Remove an element from a set. If the set does not contain the element then
/// the set is returned unchanged.
///
+/// This function runs in logarithmic time.
+///
/// ## Examples
///
/// > new() |> insert(2) |> delete(2) |> contains(1)
@@ -79,6 +82,8 @@ pub fn delete(from set: Set(element), this member: element) -> Set(element) {
/// The list has no specific ordering, any unintentional ordering may change in
/// future versions of Gleam or Erlang.
///
+/// This function runs in linear time.
+///
/// ## Examples
///
/// > new() |> insert(2) |> to_list
@@ -87,3 +92,22 @@ pub fn delete(from set: Set(element), this member: element) -> Set(element) {
pub fn to_list(set: Set(element)) -> List(element) {
map.keys(set.map)
}
+
+/// Create a new set of the elements in a given list.
+///
+/// This function runs in loglinear time.
+///
+/// ## Examples
+///
+/// > import gleam/list
+/// > [1, 1, 2, 4, 3, 2] |> from_list |> to_list |> list.sort
+/// [1, 3, 3, 4]
+///
+pub fn from_list(elements: List(element)) -> Set(element) {
+ let map = list.fold(
+ over: elements,
+ from: map.new(),
+ with: fn(k, m) { map.insert(m, k, []) },
+ )
+ Set(map)
+}