[Haskell-beginners] Streams

Francesco Ariis fa-ml at ariis.it
Thu Jul 27 10:08:03 UTC 2017


On Thu, Jul 27, 2017 at 09:33:33AM +0100, mike h wrote:
> What I'd like to do is take one item at a time from the stream. My first
> shot was 
> 
> next :: (Stream a) -> (Stream a, a)
> 
> but that means I need to keep a ref to the stream that is returned in the tuple which makes for messy code
> for subsequent calls to next. I sense that the State monad needs to be involved but I'm not sure exactly how as 
> my experiments with State still required I keep a ref to the 'new' stream. Conceptually I see this as a 'global' state
> and  next is just
> 
> next :: a
> 
> but that's 30 years of imperative programming speaking and is, I think,
> wrong! 

Hello Mike,

    I see nothing wrong with a State monad (you signature looks really like
the one inside a State monad, after all)

    next  :: Stream a -> (a, Stream a)
    next' :: s        -> (a, s       )

Many many many other ways of dealing elegantly with streams have been
proposed; check for example this article [1], which starts exactly
from your example, e.g.

    data Stream b = SCons (b, Stream b)

And then, if you are sold to the idea, exploring the various libraries
on hackage is the other half of the fun :P
-F

[1] https://blog.jle.im/entry/intro-to-machines-arrows-part-1-stream-and


More information about the Beginners mailing list