Search code examples
elm

Query only first 3 in Dict


I can't figure out an easy way to filter out just the first 3 items in this Dict

 fruit =
    fromList
        [ ( ( 0, 0 ), "apple" )
        , ( ( 0, 1 ), "orange" )
        , ( ( 0, 2 ), " " )
        , ( ( 1, 0 ), " "  )
        , ( ( 1, 1 ), " "  )
        ]

I've looked at docs for Dict but don't see any easy way to query just the first 3 into another Dict so I can then later do something with just those first 3


Solution

  • The problem is that there is not supposed to be a notion of 'first' in a Dict. In Elm, keys are ordered alphabetically, but some other languages (Go) make dictionary order random so that you are not tempted to rely upon it.

    So you should probably think about why you want to do this.

    That said, if you want to go further, the best I can suggest is

    take3Dict dict = 
        dict |> Dict.toList |> List.take 3 |> Dict.fromList