[Haskell-beginners] generating the set of all finite-valued ...

Erik Quaeghebeur equaeghe at nospammail.net
Fri Apr 24 12:20:30 EDT 2009


>> On Fri, Apr 24, 2009 at 12:16:06AM +0200, Erik Quaeghebeur wrote:
>>>
>>> 	m = mapM (\x -> [(x,-1),(x,0),(x,1)]) ['a','b','c']
>>> 	map (\x -> snd $ unzip x) m
>>>
>>> Any more direct way of doing this?

> On Fri, Apr 24, 2009 at 11:36:44AM +0100, Jan Jakubuv wrote:
>>
>> Well, you can write:
>>
>>     mapM (const [-1,0,1]) [1..3]

On Fri, 24 Apr 2009, Brent Yorgey wrote:
>
> Better yet (in my opinion), you can just write
>
>      sequence (replicate 3 [-1,0,1])
>
> which is really the same thing, since mapM = sequence . map.  Mapping
> (const [-1,0,1]) over [1..3] yields [[-1,0,1], [-1,0,1], [-1,0,1]],
> that is, (replicate 3 [-1,0,1]).  It's the 'sequence' that does the
> magic of selecting an item from each of the three lists in all
> possible ways.

Yes, now I see it, thanks to both Jan and Brent.
I can nicely generalize this to

 	n = ...
 	values = [...]
 	sequence (replicate n values)

My ideas about how I should approach other aspects of my programming task 
are also crystallizing. Now find a nice stretch of time to work things 
out...

Erik


More information about the Beginners mailing list