Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 631
Alimagadov K. Avatar asked Jan 24 '23 08:01

Alimagadov K.


2 Answers

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?)

like image 77
Will Ness Avatar answered Feb 01 '23 03:02

Will Ness


It must takes an object of "Stream" and returns an infinite list. But I don't know how to take elements of this object.

With pattern matching you can "unpack" the data wrapped in the data constructor, so something like:

streamToList :: Stream a -> [a]
streamToList (x :> xs) = …

Here x is the first item of the stream, and xs is a Stream of items.

I leave implementing the body of the clause (the part) as an exercise. You will need recursion to "walk" over the rest of the stream.

like image 28
Willem Van Onsem Avatar answered Feb 01 '23 04:02

Willem Van Onsem