elmcraft / core-extra / Set.Extra

Convenience functions for working with Set.

Toggling elements

toggle : comparable -> Set comparable -> Set comparable

If the set does not contain the element, add it. If it does contain the element, remove it.

import Set exposing (Set)

Set.Extra.toggle 1 (Set.fromList [1,2,3])
--> Set.fromList [2, 3]

Set.Extra.toggle 1 (Set.fromList [2,3])
--> Set.fromList [1, 2, 3]

Predicates

isSupersetOf : Set comparable -> Set comparable -> Basics.Bool

A set is a superset of another set if all the elements in the second set appear in the first set.

import Set exposing (Set)


Set.fromList [ 1, 2, 3 ]
    |> Set.Extra.isSupersetOf (Set.fromList [1,2,3,4,5])
--> False

Note: This is just isSubsetOf with arguments reversed. It can be handy for dealing with pipelines.

isSubsetOf : Set comparable -> Set comparable -> Basics.Bool

A set is a subset of another set if all the elements in the first set appear in the second set.

import Set exposing (Set)

Set.fromList [ 1, 2, 3 ]
    |> Set.Extra.isSubsetOf (Set.fromList [1,2,3,4,5])
--> True

areDisjoint : Set comparable -> Set comparable -> Basics.Bool

A set is disjoint from another set if they have no elements in common.

import Set exposing (Set)

Set.Extra.areDisjoint
    (Set.fromList [1,2,3])
    (Set.fromList [3,4,5])
--> False

Set.Extra.areDisjoint
    (Set.fromList [1,2,3])
    (Set.fromList [4,5,6])
--> True

Set operations

symmetricDifference : Set comparable -> Set comparable -> Set comparable

The symmetric difference between two sets is a set that contains all the elements that are in one of the two sets, but not both.

import Set exposing (Set)


Set.Extra.symmetricDifference
    (Set.fromList [1,2,3])
    (Set.fromList [3,4,5])
    --> Set.fromList [1,2,4,5]

Mapping

concatMap : (comparable -> Set comparable2) -> Set comparable -> Set comparable2

Map a given function onto a set and union the resulting set.

import Set exposing (Set)

neighbors : (Int, Int) -> Set (Int, Int)
neighbors (x, y) =
    Set.fromList
        [ (x - 1, y - 1), (x, y - 1), (x + 1, y - 1)
        , (x - 1, y),                 (x + 1, y)
        , (x - 1, y + 1), (x, y + 1), (x + 1, y + 1)
        ]

setOfPoints : Set (Int, Int)
setOfPoints =
    Set.fromList [(1,1), (0,0)]

Set.Extra.concatMap neighbors setOfPoints
--> Set.fromList
-->     [ (-1,-1), (-1,0), (-1,1)
-->     , (0,-1), (0,0), (0,1)
-->     , (0,2), (1,-1), (1,0)
-->     , (1,1), (1,2), (2,0)
-->     , (2,1), (2,2)
-->     ]

filterMap : (comparable -> Maybe comparable2) -> Set comparable -> Set comparable2

Apply a function that may succeed to all values in the set, but only keep the successes.

import Set exposing (Set)

Set.fromList ["1", "2", "a", "3"]
    |> Set.Extra.filterMap String.toFloat
--> Set.fromList [1, 2, 3]