簡體   English   中英

如何修復我的代碼以適用於所有測試?

[英]How can I fix my code to work for all of the tests?

確定列表中的項目是否都給出相同的除以 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

在每一步,您都必須檢查其余元素的奇偶校驗是否與所有之前的元素相同。 問題是,在每一步你都不再知道之前的所有元素。 他們現在迷路了。

所以你要做的就是將之前所有元素的奇偶校驗作為參數傳遞給下一步:

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函數。 它在做同樣的事情,但顯式遞歸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM