drop1 n xs | n<0 = error "Use positive numbers"
drop1 _ [] = error "Empty list"
drop1 0 xs = xs
drop1 n xs = drop1 (n-1)(tail1 xs)
我的 drop1 函式每次都會檢查。我能做些什么來檢查這個只有第一次?我該如何修改這部分:
drop1 n xs | n<0 = error "Use positive numbers"?
uj5u.com熱心網友回復:
您可以使用輔助函式:
drop1 :: Int -> [a] -> [a]
drop1 n
| n < 0 = error "Use positive numbers"
| otherwise = go n
where go _ [] = error "Empty list"
go 0 xs = xs
go k (_:xs) = go (k-1) xs
在drop1這樣的檢查一次,如果值小于0,而go僅用于檢查0和大于值0。
可能您想交換關于go _ [] = error "Empty list"and的兩個子句go 0 xs = xs,因為洗掉包含兩個專案的串列中的兩個專案可能應該回傳一個空串列,而不是錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/374168.html
標籤:哈斯克尔
上一篇:沒有sortBy的元組排序串列
下一篇:Haskell中的伯努利函式
