Last active
October 29, 2017 01:27
-
-
Save sgdan/e268467f6ef78f4367e81536021e3987 to your computer and use it in GitHub Desktop.
Create a map of sets in Elm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-- | |
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