[英]Haskell Just iterate through list
我嘗試簡單地遍歷列表並返回每個元素。
iterateList [] = error "empty list"
iterateList [a] = a
iterateList (x:xs) = x iterateList xs
在第三行,我嘗試返回第一個元素,然后遞歸調用List尾部的iterateList
。
但這不起作用。 知道為什么嗎?
示例:輸入:iterateList [1,2,3,4,5]輸出:1 2 3 4 5
我想要的只是Java中for循環的一個例子,在這里我可以對列表中的每個元素進行操作,例如打印,求和,乘法,刪除,訪問這些元素
好吧,您不能在Haskell中“刪除”任何內容,也不能修改綁定。 您可以做的是例如匯總元素:
sumList [] = 0
sumList (x : xs) = x + sumList xs
或乘以元素:
productList [] = 1
productList (x : xs) = x * productList xs
此時,您可能會意識到自己已經重復了很多次,這很煩人。 您可以提取公共部分並將差異轉換為參數:
iterateList f z [] = z
iterateList f z (x : xs) = x `f` iterateList f z xs
sumList = iterateList (+) 0
productList = iterateList (*) 1
在這里, z
表示要為空輸入列表返回的“基值”,而f
是“組合”函數,該函數告訴它如何處理元素和列表的其余部分。
打印有點復雜,因為您必須首先了解IO
工作方式(特別是,您應該了解>>
並return
),但是仍然可以完成:
doNothing = return ()
printAndThen x rest = print x >> rest
printList = iterateList printAndThen doNothing
...或直接使用值,而不是先將它們綁定到名稱:
printList = iterateList (\x rest -> print x >> rest) (return ())
最終,您會發現您剛剛重新發明了foldr
。 :-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.