[Haskell-cafe] Random question

Jonathan Cast jonathanccast at fastmail.fm
Wed Sep 24 18:02:56 EDT 2008

On Wed, 2008-09-24 at 22:44 +0100, Iain Barnett wrote:
> On 24 Sep 2008, at 10:13 pm, Evan Laforge wrote:
> >  For one approach, check
> > out 'replicate' to make copies of something, and then 'sequence' to
> > run them and return a list.

> Thanks, I haven't found anything that explains 'sequence' well yet,
> but I'll keep looking.

sequence is one of your more general-purpose loop functions in Haskell.
Frequently, the number of passes in a loop and the job of each pass are
fixed before-hand.  Standard lazy-evaluation constructs like iterate,
replicate, and map make it easy to produce a list of the passes you want
to use.  (This is the data-structure-as-control-construct pattern).
sequence then supplies the last step: it takes a list (in the principle
examples, a list of passes through some loop) and returns a loop that
goes through and executes all the passes.  In sequence, ironically

> On 24 Sep 2008, at 10:13 pm, John Van Enk wrote:
> > And the one liner:

> > (rand 1 10) >>= return . (\v -> take v [1..10])

> my last attempt before emailing was

> (rand 1 10 ) >>= (\x -> take x [1..10])

> So close! :)

> I can see now, with all the examples, why the return is needed, but
> not why the composition operator is. Something for me to look into.

Btw: the composition operator isn't needed.  You can inline it into your
example and get

    (rand 1 10) >>= (\ v -> return ((\ v -> take v [1..10]) v))

(which is equivalent to the clearer

    (rand 1 10) >>= (\ v -> return (take v [1..10]))

by a step closely related to inlining (beta-contraction, to be specific)).

I don't know why composition was used in this case.  Using the version

   (\ v -> take v [1..10]) <$> (rand 1 10)

and using the definition

    f <$> a = a >>= return . f

gives rise to it.


More information about the Haskell-Cafe mailing list