我應該如何對串列進行磁區?(不使用庫)
例如 :
輸入
[0,1,1,1,1,0,0,0,1]
輸出
[[0,1,1],[1,1,0],[0,0,1]]
uj5u.com熱心網友回復:
您可以在n元素后遞回地每次拆分串列,然后產生第一個專案,并遞回剩余的專案,所以:
partition :: Int -> [a] -> [[a]]
partition n = go
where go [] = []
go xs = ys : go yss
where (ys, yss) = splitAt n xs
例如:
ghci> partition 3 [0,1,1,1,1,0,0,0,1]
[[0,1,1],[1,1,0],[0,0,1]]
uj5u.com熱心網友回復:
我已經設法通過在串列理解中使用 take 和 drop 來做到這一點。(我遇到了麻煩,因為我先寫了 take first and drop second,給了我不正確的磁區)
這對我有用
[ drop ((size)*x) (take ((size)*(x 1)) (list)) | x<-[0..size]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/482699.html
標籤:哈斯克尔
