1

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.

1

2 Answers 2

2

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*

Sign up to request clarification or add additional context in comments.

1 Comment

I found Singleton which I think is the same than a fromList with one element. But well now is pretty clear the API. Thanks
1

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")]

4 Comments

I just saw the fromList operator, but I was wondering if it was a simple way without have to create a list. Still is what I´m doing already, thanks a lot for the answer
Unfortunately, the syntax is little bit verbose. You can make it a little bit less verbose by enabling OverloadedLists extension. You can then omit calling fromList. I'll add it to my answer.
myMap = [(5,"a"), (3,"b"), (5, "c")] how is possible that this is not getting conflict with a List of tuple of (Int, String) ??!
Because myMap is explicitly typed as Map Int String. If the type can be derived from context (from usage), it can be omitted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.