Skip to content

Instantly share code, notes, and snippets.

@sgdan
Created October 29, 2017 04:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgdan/016db8c339ab7f89abd3a0d8521155cb to your computer and use it in GitHub Desktop.
Save sgdan/016db8c339ab7f89abd3a0d8521155cb to your computer and use it in GitHub Desktop.
Iterating over a map in Elm
{--
Some Elm code for various ways to iterate over a map
Run at http://elm-lang.org:1234/try
--}
import Html exposing (text, div, br)
import Dict exposing (Dict)
import String exposing (toUpper)
initial = Dict.fromList [(1, "one"), (2, "two")]
foldToString = Dict.foldl (
\k v acc -> acc ++ "<" ++ (toString k) ++ "|" ++ v ++ ">"
) "" initial
mapToDict = Dict.map (
\k v -> (toUpper) v
) initial
foldToList = Dict.foldl (
\k v acc -> ((toString k) ++ ": " ++ v) :: acc
) [] initial
main = div [] [
"initial: " ++ toString initial |> text, br[][],
"foldToString: " ++ toString foldToString |> text, br[][],
"mapToDict: " ++ toString mapToDict |> text, br[][],
"foldToList: " ++ toString foldToList |> text, br[][]
]
{--
Should see the following output:
initial: Dict.fromList [(1,"one"),(2,"two")]
foldToString: "<1|one><2|two>"
mapToDict: Dict.fromList [(1,"ONE"),(2,"TWO")]
foldToList: ["2: two","1: one"]
--}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment