# producing and consuming lists

**Jorge Adriano
**
jadrian@mat.uc.pt

*Wed, 6 Nov 2002 01:32:21 +0000*

>* streams :: (Int -> Bool, Int -> Bool) -> (Int,Int) ->
*>* [(Maybe Int,Maybe Int)]
*>* streams (p,q) (x,y)
*>*
*>* | p x && p y =3D (Just x , Just y ) : xs
*>* | p x =3D (Just x , Nothing) : xs
*>* | p y =3D (Nothing, Just y ) : xs
*>* | otherwise =3D xs
*>*
*>* where xs =3D streams (p,q) ((x+y),(y-x))
*
Yeap, in fact I thought about it when answering Toms answer.
Doesn't seem good enough in more general cases though,
Like:=20
streams :: (Int->Bool, Int->Bool)->(Int, Int)->([Int],[Int])
streams (p,q) (x,y) =3D (xs',ys')
where
(xs,ys) =3D streams (p,q) ((x+y),(y-x))
xs' =3D if p x then x:xs else zs++xs <-------
ys' =3D if q y then y:xs else ys
zs =3D some_other_stream <----------
Or:
streams :: (Int->Bool, Int->Bool)->(Int, Int)->([Int],[Int])
streams (p,q) (x,y) =3D (xs',ys')
where
(xs,ys) =3D streams (p,q) ((x+y),(y-x))
xs' =3D if p x then x:xs else zs -- <------------
ys' =3D if q y then y:xs else ws -- <-----------
zs =3D ... some other_stream -- <---
ws=3D ... yet_another_stream -- <---
>* With this setup, I think you can write your own writefile function whic=
*h
>* looks something like:
*>* I think, but I'm not sure, that this will allow the old stuff to be
*>* garbage collected. In practice, you don't get too much useless junk
*>* generated because we don't append the (Nothing,Nothing) pair to the lis=
*t
Nice observation, I missed that one since I didn't paired both lists :)
But like I just showed, sometimes paring them may not be a natural approa=
ch=20
though...
>* (erm, "prepend"). But what's more important, I think you only evaluate
*>* the same amount of each at any given time, thus allowing GC to gobble u=
*p
>* the old stuff.
*Exactly
>* An expert might be able to prove me wrong, though, or you could try thi=
*s
>* and profile it and see if it works or not :)
*I haven't tested it yet either but seems to me like it should work, in th=
is=20
particular example.
I was hoping I could somehow take advantage of the fact that the order in=
=20
which I want to consume the lists doesn't matter. I thought about concurr=
ency=20
but it doesn't seem to work.
J.A.