確定串列中的專案是否都給出相同的除以 2 的余數。
我的代碼在 mod 為 1 時作業,但當 mod 為 0 時它不起作用。我必須添加什么才能作業?一個 if - else 陳述句還是別的什么?
sameParity :: [Int] -> Bool
sameParity [] = True
sameParity (x: xs)
| x `mod` 2 == 1 = sameParity xs
| x `mod` 2 == 0 = sameParity xs
| otherwise = False
例子:
以下每個測驗用例都必須給出 True:
sameParity [] == 真
sameParity [1..10] == False
sameParity [1,3..10] == True
sameParity [2, 42, 0, 8] == 真
sameParity (1: [2, 42, 0, 8]) == False
uj5u.com熱心網友回復:
在每一步,您都必須檢查其余元素的奇偶校驗是否與所有之前的元素相同。問題是,在每一步你都不再知道之前的所有元素。他們現在迷路了。
所以你要做的就是將之前所有元素的奇偶校驗作為引數傳遞給下一步:
allHaveParity [] _ = True
allHaveParity (x:xs) prevItemsParity = (x `mod` 2 == prevItemsParity) && (allHaveParity xs prevItemsParity)
> allHaveParity [1,3] 1
True
> allHaveParity [2,4] 0
True
> allHaveParity [1,2] 1
False
但是,當然,這現在非常不方便,因為現在您必須傳入“預期的”奇偶校驗,而不僅僅是讓函式計算出來。
但不要害怕!只需將此函式包裝在另一個函式中,它將采用第一項的奇偶校驗并將其傳遞下去:
sameParity [] = True
sameParity (x:xs) = allHaveParity xs (x `mod` 2)
現在可以很容易地觀察到,一旦我們有了第一個專案的奇偶校驗,我們就可以使用現有all函式來檢查所有其他專案:
sameParity [] = True
sameParity (x:xs) =
let firstParity = x `mod` 2
in all (\a -> (a `mod` 2) == firstParity) xs
并丟棄該allHaveParity功能。它正在做同樣的事情,但顯式遞回。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/343745.html
上一篇:將顯示功能功能分配給另一個關鍵字
下一篇:在無限串列的串列上使用foldr
