Haskell 如何删除列表中的所有 0 直到其中一个元素 /= 0?
Haskell how to drop all 0 of the list until one of the elements /= 0?
我是 Haskell 的新手,我正在尝试弄清楚如何编写代码,在列表的某个元素 >0 之前删除所有零。
例如:
输入:[0,0,5,6,0]
输出:[5,6,0]
到目前为止我已经写了这个:
zeroUntil :: [Int] -> [Int]
zeroUntil [] = []
zeroUntil (x:xs)
| x == 0 = drop x (xs)
| otherwise = zeroUntil xs
但不知何故我得到了 [5,6,0] [ ].
任何人都可以解释一下我做错了什么吗?
zeroUntil :: [Int] -> [Int]
zeroUntil [] = []
zeroUntil (x:xs)
| x == 0 = drop x (xs)
| otherwise = [x] ++ (zeroUntil xs)
您必须将第一个元素 (x
) 添加到由递归调用 return 编辑的列表中,否则您 return 一个空列表。
您可以使用 dropWhile :: (a -> Bool) -> [a] -> [a]
并因此丢弃物品,只要这些物品为零即可:
zeroUntil :: [Int] -> [Int]
zeroUntil = <b>dropWhile (0 ==)</b>
如果要删除零直到元素大于零,可以使用递归。如果这些元素小于零,那么你的递归案例应该产生元素:
zeroUntil :: [Int] -> [Int]
zeroUntil [] = []
zeroUntil (0:xs) = zeroUntil xs
zeroUntil (x:xs)
| x > 0 = x : xs -- ← end of recursion, return the list
| otherwise = x : zeroUntil xs -- ← yield x and recurse
例如:
Prelude> zeroUntil [0,0,5,6,0]
[5,6,0]
Prelude> zeroUntil [0,-1,5,6,0]
[-1,5,6,0]
我是 Haskell 的新手,我正在尝试弄清楚如何编写代码,在列表的某个元素 >0 之前删除所有零。
例如:
输入:[0,0,5,6,0]
输出:[5,6,0]
到目前为止我已经写了这个:
zeroUntil :: [Int] -> [Int]
zeroUntil [] = []
zeroUntil (x:xs)
| x == 0 = drop x (xs)
| otherwise = zeroUntil xs
但不知何故我得到了 [5,6,0] [ ].
任何人都可以解释一下我做错了什么吗?
zeroUntil :: [Int] -> [Int]
zeroUntil [] = []
zeroUntil (x:xs)
| x == 0 = drop x (xs)
| otherwise = [x] ++ (zeroUntil xs)
您必须将第一个元素 (x
) 添加到由递归调用 return 编辑的列表中,否则您 return 一个空列表。
您可以使用 dropWhile :: (a -> Bool) -> [a] -> [a]
并因此丢弃物品,只要这些物品为零即可:
zeroUntil :: [Int] -> [Int]
zeroUntil = <b>dropWhile (0 ==)</b>
如果要删除零直到元素大于零,可以使用递归。如果这些元素小于零,那么你的递归案例应该产生元素:
zeroUntil :: [Int] -> [Int]
zeroUntil [] = []
zeroUntil (0:xs) = zeroUntil xs
zeroUntil (x:xs)
| x > 0 = x : xs -- ← end of recursion, return the list
| otherwise = x : zeroUntil xs -- ← yield x and recurse
例如:
Prelude> zeroUntil [0,0,5,6,0]
[5,6,0]
Prelude> zeroUntil [0,-1,5,6,0]
[-1,5,6,0]