[英]Haskell need help understanding stream
我有這個代碼,這些功能已經完成:
代碼如下:
data Stream a = Cons a (Stream a)
streamToList :: Stream a -> [a]
streamToList (Cons x xs) = x : streamToList xs
streamIterate :: (a -> a) -> a -> Stream a
streamIterate f x = Cons x (streamIterate f (f x))
streamIterLeave :: Stream a -> Stream a -> Stream a
streamIterLeave (Cons x xs) ys = Cons x (streamIterLeave ys xs)
現在我遇到的問題是我不知道如何在 ghci 上檢查此代碼。 更具體地說,如何在命令行中輸入 stream?
例如,我嘗試streamToList [1,2,3]
; streamToList (1,2,3)
; streamToList 1,2,3
並且它們似乎都沒有工作。
非常感謝您的幫助!
幾種方式。 最簡單的就是使用undefined
:
> take 2 $ streamToList $ Cons 1 $ Cons 2 undefined
[1,2]
您可以在提示符下定義命名流,
> let { one = Cons 1 two ; two = Cons 2 one }
或多線輸入,
> :{
| one = Cons 1 two
| two = Cons 2 one
| :}
> take 5 $ streamToList one
[1,2,1,2,1]
並且您可以使用您的streamIterate
如評論中所示或使用foldr
從列表中創建您的流,
> take 5 $ streamToList $ streamIterate (+1) 0
[0,1,2,3,4]
> intS = foldr Cons undefined [1..]
> take 5 $ streamToList intS
[1,2,3,4,5]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.