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

Brent Yorgey byorgey at seas.upenn.edu
Fri Apr 24 09:24:00 EDT 2009


On Fri, Apr 24, 2009 at 11:36:44AM +0100, Jan Jakubuv wrote:
> On Fri, Apr 24, 2009 at 12:16:06AM +0200, Erik Quaeghebeur wrote:
> >
> > Aha. Great. Thanks, Jan. And now I realized that I don't really care 
> > about the domain, so I said:
> >
> > Prelude> let m = mapM (\x -> [(x,-1),(x,0),(x,1)]) ['a','b','c']
> > Prelude> map (\x -> snd $ unzip x) m
> > [[-1,-1,-1],[-1,-1,0],[-1,-1,1],[-1,0,-1],[-1,0,0],[-1,0,1],[-1,1,-1],[-1,1,0],[-1,1,1],[0,-1,-1],[0,-1,0],[0,-1,1],[0,0,-1],[0,0,0],[0,0,1],[0,1,-1],[0,1,0],[0,1,1],[1,-1,-1],[1,-1,0],[1,-1,1],[1,0,-1],[1,0,0],[1,0,1],[1,1,-1],[1,1,0],[1,1,1]]
> >
> > Any more direct way of doing this? (Still trying to understand how the  
> > mapM works... I've found it's sequence.map, but that doesn't really 
> > help.)
> >
> 
> Well, you can write:
> 
>     mapM (const [-1,0,1]) [1..3]

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.

-Brent


More information about the Beginners mailing list