繁体   English   中英

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 = ...

我已将这两个案例留给您实施。

您还可以添加n为零的情况。 在这种情况下,您可以提前返回列表,因为没有一个奇数是最零的。

递归应该可以帮助您:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM