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?
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?)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With