Haskell - 从列表中删除第 N 个奇数

Haskell - Remove the Nth odd number from a list

我一直想知道是否有任何方法可以从列表中删除第 N 个奇数

例如:

removeOdd 2 [2,4,3,6,5,8] == [2,4,3,6,8]

您有 2 个基本情况,列表为空和列表不为空。对于不为空的列表,你有 3 个子情况,n == 1(这意味着你需要删除下一个奇数)并且数字是奇数,n > 1 并且数字是奇数,并且数字不是奇数。

removeNthOdd _ [] = []
removeNthOdd n (x:xs)
  | x `mod` 2 == 1 && n == 1 = xs
  | x `mod` 2 == 1 = ...
  | otherwise = ...

我把这2个案例留给你去实现。

您还可以添加 n 为零的情况。在那种情况下,您可以尽早 return 列表,因为没有一个奇数是最零的。

递归应该可以帮助你:

removeNthOdd :: Int -> [Int] -> [Int]
-- basecase of an empty list
removeNthOdd n [] = []
removeNthOdd n (x : xs)
  -- odd number to remove is found, just return the rest of the list
  | odd x && n == 1 = xs
  -- odd number found, but not the one we want to remove
  -- so we decrement n to reach the case before
  | odd x && n > 0 = x : removeNthOdd (n - 1) xs
  -- x is even, so just continue
  | otherwise = x : removeNthOdd n xs

*Main> removeNthOdd 2 [2,4,3,6,5,8] == [2,4,3,6,8]
True

考虑下一次问一个具体的问题以及你自己做了什么,例如粘贴一些代码,以达到您的目标。