简体   繁体   中英

Haskell Streams (Comonadic): Infinite?

I've seen streams used as the default example of a comonad, but I can't quite figure how they're infinite, but not.

Assume we have the data constructor ( from here )

data Stream a = a :> Stream a

How do we finally finish off a stream? Do we write it w/ an undefined at the end? I get that the language is lazy, but somewhere the knot must be cut, right? Am I just wrong?

A stream is inherently infinite; you can't create a finite stream. Compare Stream and List :

data List   a = Empty | a :  List a
data Stream a =         a :> Stream a

You can create a finite list because of Empty constructor; it is possible to create a List value without referring to another List value. A Stream value, on the other hand, can only be created by using another Stream value. Any time you pattern match on a Stream , you get a value of type a and another Stream value.

"Finishing" a stream simply means you stop pulling values from it, not that you ever reach the "end" of the stream.

In practice, this means you cannot instantiate a full stream in memory; you can only build it on-demand, typically by calling a function to generate remainder of the stream when pattern matching on the :> constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM