[L06 MoreParser] Questions - SPOILER ALERT

37 views
Skip to first unread message

Riaan Rottier

unread,
Jul 30, 2013, 6:40:30 AM7/30/13
to haskell-...@googlegroups.com
Question about Exercise 6

-- Write a function that parses the given string (fails otherwise).
-- ~~~ Use is and mapM ~~~

So I blindly tried the hint and got 

string ::  String  -> Parser String
string = mapM is

Which worked!  Can someone please explain to me why it works.

R

Tony Morris

unread,
Jul 30, 2013, 7:05:26 AM7/30/13
to haskell-...@googlegroups.com
The mapM function is sometimes also called traverse.

It is well described in this paper:
http://www.cs.ox.ac.uk/jeremy.gibbons/publications/iterator.pdf

Or if you prefer Scala:
http://etorreborre.blogspot.com/2011/06/essence-of-iterator-pattern.html

--
Tony Morris
http://tmorris.net/

Tony Morris

unread,
Jul 30, 2013, 7:08:45 AM7/30/13
to haskell-...@googlegroups.com
On 30/07/13 20:40, Riaan Rottier wrote:
You might also notice that mapM has the same type as map, but with 'm'
appearing in every return position.

map :: (a -> b) -> [a] -> [b]
mapM :: (a -> m b) -> [a] -> m [b]

This is the same pattern as was seen in earlier functions:

filter :: (a -> Bool) -> [a] -> [a]
filterM :: (a -> m Bool) -> [a] -> m [a]

replicate :: Int -> a -> [a]
reeplicate :: Int -> a -> m [a]

find :: (a -> Bool) -> [a] -> Maybe a
findM :: (a -> m Bool) -> [a] -> m (Maybe a)

Riaan Rottier

unread,
Jul 31, 2013, 11:59:55 PM7/31/13
to haskell-...@googlegroups.com, tmo...@tmorris.net
Thank you, I only followed about 20% of the paper but it seems like we have 

mapM = sequencePaser . fmap f

Am I on the right track?

R

Tony Morris

unread,
Aug 1, 2013, 12:02:35 AM8/1/13
to Riaan Rottier, haskell-...@googlegroups.com, tmo...@tmorris.net
Yes, mapM is indeed fmap then sequence.

Also, sequence is mapM id.

In other words, mapM and sequence have the same power.
Reply all
Reply to author
Forward
0 new messages