haskellstreamalgebraic-data-typescustom-data-type

Stream data type implementation in Haskell


I have course for Haskell programming at my university. And I must implement my own datatype "Stream" and its some functional:

data Stream a = a :> Stream a

I have problems to implement a function "streamToList":

streamToList :: Stream a -> [a]

It must take an object of "Stream" and return an infinite list. But I don't know how to take elements of this object. How can I take the elements of this stream?

Also, I want to ask: what is the way to initialize an object of this datatype?


Solution

  • You have defined your data type as

    data Stream a = a :> Stream a
    

    This serves as a pattern, a template for how it can be used. "Used" means, both created and accessed. In other words, interacted with.

    Values of this type can be accessed with the pattern to the left of = in definitions,

    foo (a :> restOfAs) = a : foo restOfAs
    

    (what's the type of this function?)

    Values of this type can be created using it as a code pattern to the right of = in definitions, e.g.

    bar i = i :> bar (i+1)
    

    or

    baz [x]    = x :> baz [x]
    baz (x:xs) = x :> baz xs
    baz []     = error "can't be empty"
    

    or

    quux x = xs  where  
             xs = x :> xs
    

    (what are the types of these functions?)