Skip to content

Instantly share code, notes, and snippets.

@cobalamin
Last active July 28, 2016 20:23
Show Gist options
  • Select an option

  • Save cobalamin/feceff0823e57094d3490a5f9ed8eb69 to your computer and use it in GitHub Desktop.

Select an option

Save cobalamin/feceff0823e57094d3490a5f9ed8eb69 to your computer and use it in GitHub Desktop.
Selecting a set of keys from an existing Dict to make a new one. Fails silently if key doesn't exist in old dict.
module DictSelect exposing (..)
import Dict exposing (Dict)
import Set
select : List comparable -> Dict comparable v -> Dict comparable v
select keys dict =
List.foldr (putIfIn dict) Dict.empty keys
putIfIn : Dict comparable v -> comparable -> Dict comparable v -> Dict comparable v
putIfIn origDict key newDict =
case Dict.get key origDict of
Just val ->
Dict.insert key val newDict
Nothing ->
newDict
-- much simpler, but traverses whole original Dict
select' : List comparable -> Dict comparable v -> Dict comparable v
select' keys dict =
Dict.filter (\k _ -> List.member k keys) dict
-- version that uses Sets to check keys, very possibly faster in some unlikely scenarios
select'' : List comparable -> Dict comparable v -> Dict comparable v
select'' keys dict =
let
keySet =
Set.fromList keys
in
Dict.filter (\k _ -> Set.member k keySet) dict
------ Examples!
-- Dict.fromList [("eleet",31337),("fortytwo",42),("fortytwotimesten",420),("leet",1337)]
dictA =
Dict.fromList [ ( "fortytwo", 42 ), ( "fortytwotimesten", 420 ), ( "leet", 1337 ), ( "eleet", 31337 ) ]
-- Dict.fromList [("fortytwo",42),("leet",1337)]
dictB =
select [ "fortytwo", "leet", "not_in_dict" ] dictA
dictB' =
select' [ "fortytwo", "leet", "not_in_dict" ] dictA
dictB'' =
select'' [ "fortytwo", "leet", "not_in_dict" ] dictA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment