简体   繁体   中英

Conversion between two stream types

I have a question regarding converting between two datatypes in Haskell.

Consider the following two datatypes

 data Stream a = Cons a (Stream a) data Stream2 a = ST {shead :: a, stail :: Stream2 a} 

Q2: Write

 sToS2 :: Stream a -> Stream2 a s2ToS :: Stream2 a -> Stream a 

that convert between the two representations of streams

The first thing that I am having trouble with is the Stream datatype, We can see this is a recursive datatype but there is no base case, which makes me wonder if this is somehow infinite and how I could go about creating a stream datatype. Furthermore the constructor for Stream2 is given in record syntax where one of the fields is also something of type Stream2. I understand there was a question similar to time where

data Ab = A | B
data Cd = C | D

fromAb :: Ab -> Cd
fromAb A = C
fromAb B = D

toAb :: Cd -> Ab
toAb C = A
toAb D = B

but I am unsure how I can apply the answers from this question to my particular confusion.

there is no base case, which makes me wonder if this is somehow infinite

It is!

and how I could go about creating a stream

Recursively! Haskell is nonstrict, so this is no problem. Behold:

successors :: Num a => a -> Stream a
successors start = Cons start $ successors $ start + 1

λ> case successors 1 of Cons _ (Cons _ (Cons x _)) -> x
3

the constructor for Stream2 is given in record syntax where one of the fields is also something of type Stream2

Indeed. Aside from using the record sugar, the Stream2 type is identical (or, more precisely, isomorphic ) to Stream . We might line things up a bit to make the parallels more visually obvious:

data Stream  a = Cons            a           (Stream  a)
data Stream2 a = ST   { shead :: a, stail ::  Stream2 a }
--   [  1  ]     [ 2 ]          [3]           [   4   ]
  1. The type
  2. The type's only constructor
  3. Type of the first constructor parameter
  4. Type of the second constructor parameter

You can ignore the record syntax when you're writing the conversions.

sToS2 :: Stream  a -> Stream2 a
s2ToS :: Stream2 a -> Stream  a

sToS2 (Cons x xs) = ST   x $ sToS2 xs
s2ToS (ST   x xs) = Cons x $ s2ToS xs

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