paul
paul

Reputation: 13471

Haskell Create key value map

I have to be kind of dumb, but watching all blogs and documentation https://hackage.haskell.org/package/containers-0.4.2.0/docs/Data-Map.html

I cannot figure how to create a simple Map collection with a simple key -> value.

Sorry I´m very newby.

Upvotes: 1

Views: 2802

Answers (2)

max630
max630

Reputation: 9238

you should look for functions with signature like a -> b -> ... -> Map k v, where none of a,b... (the input parameters) is a Map. From Data.Map such are empty, which creates empty map, singleton, which creates map with one element, and all flavours of from*List*

Upvotes: 2

Erik Cupal
Erik Cupal

Reputation: 2935

First, make sure you have containers package installed via cabal or stack. I am assuming you want to use the latest version of the package (0.5.11.0). The link on hackage that you posted points to very old version of the package.

Then import the Data.Map

import qualified Data.Map.Strict as Map
import Data.Map (Map())

Use fromList function to create a map

-- map with ints as keys and strings as values
myMap :: Map Int String
myMap = Map.fromList [(5,"a"), (3,"b"), (5, "c")]

If you want to cut the boilerplate, you can use OverloadedLists extension.

-- put extensions at the top of your file
{-# LANGUAGE OverloadedLists #-}

import qualified Data.Map.Strict as Map
import Data.Map (Map())

-- map with ints as keys and strings as values
myMap :: Map Int String
myMap = [(5,"a"), (3,"b"), (5, "c")]

Upvotes: 1

Related Questions