Skip to content

Instantly share code, notes, and snippets.

@Warry
Last active November 19, 2019 04:15
Show Gist options
  • Save Warry/b4382a5b4373de57f5ba to your computer and use it in GitHub Desktop.
Save Warry/b4382a5b4373de57f5ba to your computer and use it in GitHub Desktop.
Convert a List of objects into a Dict (≈ Map) using an object's property as key, in a type safe way with ELM
import Dict
-- The transformation function
listToDict : (a -> comparable) -> [a] -> Dict.Dict comparable a
listToDict getKey values = Dict.fromList (map (\v -> (getKey v, v)) values)
-- Demo type
type FooBar =
{ foo : String
, bar : Int
}
-- Demo data
fooBars : [FooBar]
fooBars =
[ { foo = "tata", bar = 1 }
, { foo = "tete", bar = 2 }
, FooBar "titi" 3
, FooBar "toto" 4
]
-- Transform demo List to a Dict, using the `foo` property (String)
dict : Dict.Dict String FooBar
dict = listToDict .foo fooBars -- .foo is safe here
-- Transform demo List to a Dict, using the `bar` property (Int)
dict2 : Dict.Dict Int FooBar -- So is Int here !
dict2 = listToDict .bar fooBars
-- Won't compile:
-- err : Dict.Dict Boolean FooBar
-- err = listToDict .bar fooBars
-- err : Dict.Dict String FooBar
-- err = listToDict .bazzzzzzz fooBars
-- Render result
main = flow down [ (asText dict), (asText dict2) ]
@Warry
Copy link
Author

Warry commented Nov 6, 2014

@jesse-c
Copy link

jesse-c commented Oct 11, 2017

Hey Warry, we're looking to use this snippet for something at work, and while it's a boring question, I have to ask—what code is this snippet license under?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment