[Haskell-beginners] a problem with maps

Yitzchak Gale gale at sefer.org
Sun Jul 24 00:46:43 CEST 2011


Ertugrul Soeylemez wrote:
>>   fromAmbList :: Ord k => [(k, a)] -> Map k [a]
>>    fromAmbList = M.fromListWith (++) . map (second pure)

David Place wrote:
> If I am reading your code, I may look up second
> and find it in Control.Arrow. I have to learn about
> Arrows to understand your code?  And pure makes
> me need to study the Applicative class.

For this, there is no need to get into the issue
of when is the right time to learn about Arrows and
Applicative.

The functions "first" and "second" from Control.Arrow
are quite common in Haskell. They are simple and
convenient, they don't require knowing
anything about Arrows when used with plain old
functions and tuples, and using them doesn't create
any library dependencies. Whether or not you use them
in your own style is your own choice (I have gone through
different periods either way, currently I don't use them
much), but it's a good idea to be familiar with them.

Here are their type signatures, translated into the usual
non-Arrows style:

first :: (a -> a') -> (a, b) -> (a', b)
second :: (b -> b') -> (a, b) -> (a, b')

As for "pure", my opinion is that it's not very good style
to use it in this context. We're not using the Applicative
structure of lists in any significant way here, we're just
creating singleton lists. So I would just use (: []).

That said, "pure" is also very simple. For lists, we
have:

pure = return = (: []) -- for lists only

Another simple but useful Haskell fact.

-Yitz



More information about the Beginners mailing list