[Haskell-beginners] lifting to applicative: recomputing an argument each time it is used?

Chaddaï Fouché chaddai.fouche at gmail.com
Sat Sep 8 17:40:39 CEST 2012


On Sat, Sep 8, 2012 at 4:49 PM, Iain Nicol <iain at thenicols.net> wrote:

> Hi,
>
> I think I'm trying to lift 'Data.List.intersperse' (to applicative or a
> monad) in such a way that its (first) argument is recomputed each time
> it is used.  I'm hoping that there's a reusable, elegant or abstract,
> approach for this that I'm unaware of.
>

Instead of using intersperse, just generate two list and interlace them
(interlace is easy to write, though not in Data.List :

> interlace (x:xs) (y:ys) = x : y : interlace xs ys
> interlace xs [] = xs
> interlace [] ys = ys
>
> listOfN n g = replicateM n g
>
> mixIntersperse genSep genWord = do
>   n <- arbitrary
>   ws <- listOfN n genWord
>   ss <- listOfN (n-1) genSep
>   return $ interlace ws ss

That seems more elegant to me but you'll judge :)

-- 
Jedaï
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120908/5df5f56f/attachment.htm>


More information about the Beginners mailing list