Skip to content

Instantly share code, notes, and snippets.

@Warry Warry/propMap.elm
Last active Nov 19, 2019

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

Warry commented Nov 6, 2014

@jesse-c

This comment has been minimized.

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
You can’t perform that action at this time.