Skip to content

Instantly share code, notes, and snippets.

@sgdan
Last active October 29, 2017 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgdan/e268467f6ef78f4367e81536021e3987 to your computer and use it in GitHub Desktop.
Save sgdan/e268467f6ef78f4367e81536021e3987 to your computer and use it in GitHub Desktop.
Create a map of sets in Elm
{--
Some Elm code for a map of sets. This maps prices to the set of items
with that price.
Run at http://elm-lang.org:1234/try
--}
import Html exposing (text, div, br)
import Dict exposing (Dict)
import Set exposing (Set)
type alias ItemSet = Set String -- set of named items
type alias ItemsByPrice = Dict Int ItemSet -- map prices to sets of item names
-- Add item to existing set for that price, or create a new set if there are no existing ones
addItem: String -> Maybe ItemSet -> Maybe ItemSet
addItem newItem existingItems =
case existingItems of
Just existingItems -> Set.insert newItem existingItems |> Just
Nothing -> Set.fromList [newItem] |> Just
initial: ItemsByPrice
initial = Dict.empty
-- add $2 apple and $3 pear
-- Note that (addItem "value") is a curried function in the form that update expects
-- in this case of type: Maybe ItemSet -> Maybe ItemSet
couple = Dict.update 2 (addItem "apple") initial
|> Dict.update 3 (addItem "pear")
-- add fruit with similar prices
similar = Dict.update 2 (addItem "banana") couple
|> Dict.update 3 (addItem "orange")
main = div [] [
"initial: " ++ toString initial |> text, br[][],
"couple: " ++ toString couple |> text, br[][],
"similar: " ++ toString similar |> text, br[][]
]
{--
Should see the following output:
initial: Dict.fromList []
couple: Dict.fromList [(2,Set.fromList ["apple"]),(3,Set.fromList ["pear"])]
similar: Dict.fromList [(2,Set.fromList ["apple","banana"]),(3,Set.fromList ["orange","pear"])]
--}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment