[英]Need help understanding Haskell recursive division function
recdiv :: Integer -> [Integer] -> [Integer] -> [Integer]
recdiv x numlist divisors
| numlist == [] = divisors
| mod x (last numlist) == 0 = recdiv x (init numlist) ((last numlist):divisors)
| otherwise = recdiv x (init numlist) (divisors)
divides :: Integer -> [Integer]
divides x
| x == 0 = error "Visi skaiciai"
| x > 0 = recdiv x [1..x] []
| x < 0 = recdiv (abs x) [1..(abs x)] []
此函數的目的是查找輸入數字的所有除數。
我了解除法函數中發生的情況,但我在使用 recdiv 函數時遇到了一些麻煩。
正如我在第三行中所理解的,我們檢查 numlist 是否為空,如果是,我們也將除數列表設為空。
但是,我無法真正理解第 4 行和第 5 行中發生的事情。 有人可以解釋並幫助我理解嗎?
這是一個更好的版本。
recdiv :: Integer -> [Integer] -> [Integer]
recdiv x numlist = case numlist of
[] -> []
y : ys
| mod x y == 0 = y : recdiv x ys
| otherwise = recdiv x ys
divides :: Integer -> [Integer]
divides 0 = error "Visi skaiciai"
divides x = recdiv (abs x) [1..(abs x)]
但是沒有人會這樣寫recdiv
; 他們會用
recdiv x = filter $ \y -> mod x y == 0
不要試圖理解你正在查看的代碼; 把它扔掉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.