我想將一個串列分成具有 n 個元素的組。例如:
n = 2
[1, 2, 3, 4, 5, 6] ->[[1, 2], [3, 4], [5,6]]
n = 3
[1, 2, 3, 4, 5, 6] -> [[1, 2, 3] [4, 5, 6]]
我嘗試實作一個函式,如果 n 為 0 或大于串列的長度,則回傳 n,如果 n 小于串列的長度,則回傳擬合串列。
split :: Int -> [a] -> Either Int [[a]]
split n [a]
|n <= lenght [a] = Right n (take n [a]) : (split n (drop n [a]))
|n == 0 = Left n
|otherwise = Left n
但是,我收到“變數不在范圍內”錯誤。我已經嘗試過了,但我被卡住了。我在資料型別上犯了錯誤嗎?
uj5u.com熱心網友回復:
你有一個錯字lenghtvs. length,但如果我們改變它,仍然有錯誤。
如果我們看一下,Right n (take n [a])我們可以看到這一點,Right并且Left只接受一個論點。
您的模式split n [a]也只匹配具有單個元素的串列。
讓我們把它分解成更小的部分。創建一個拆分串列的函式很簡單。
split' n [] = []
split' n lst = take n lst : (split' n $ drop n lst)
Prelude> split' 3 [1,2,3,4,5,6]
[[1,2,3],[4,5,6]]
現在可以很簡單地將此本地化以split合并您指定的檢查并回傳所需的Either型別。
split :: Int -> [a] -> Either Int [[a]]
split n [] = Left n
split n lst
| n == 0 || n > length lst = Left n
| otherwise = Right lst'
where
split' n [] = []
split' n lst = take n lst : (split' n $ drop n lst)
lst' = split' n lst
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/527083.html
標籤:列表哈斯克尔类型分裂
上一篇:Python中的正則運算式匹配
