6

我已经自学了一个月左右的 Haskell,今天我正在阅读第 16 个问题的解决方案并提出了一个问题。

这是一个链接:http ://www.haskell.org/haskellwiki/99_questions/Solutions/16

基本上,这个问题要求创建一个从列表中删除每个第 N 个元素的函数。例如,

*Main> dropEvery "abcdefghik" 3

"abdeghk"

链接中的第一个解决方案是

dropEvery :: [a] -> Int -> [a]
dropEvery [] _ = []
dropEvery (x:xs) n = dropEvery' (x:xs) n 1 
  where
       dropEvery' (x:xs) n i = (if (n `divides` i) then [] else [x])++ (dropEvery' xs n (i+1))
       dropEvery' [] _ _ = []
       divides x y = y `mod` x == 0

我的问题是为什么 dropEvery 定义了空列表的情况,而 dropEvery' 可以处理空列表?我认为dropEvery [] _ = []可以简单地消除并修改一些其他句子,如下所示应该与上面完全相同并且看起来更短。

dropEvery :: [a] -> Int -> [a]
dropEvery xs n = dropEvery' xs n 1 
  where
       dropEvery' (x:xs) n i = (if (n `divides` i) then [] else [x])++ (dropEvery' xs n (i+1))
       dropEvery' [] _ _ = []
       divides x y = y `mod` x == 0

谁能帮我弄清楚这一点?

4

1 回答 1

7

我认为它们是相同的,作者可以按照您的建议简化代码。对于它,我用QuickCheck尝试了两个版本,它们似乎是一样的。


import Test.QuickCheck

dropEvery :: [a] -> Int -> [a]
dropEvery [] _ = []
dropEvery (x:xs) n = dropEvery' (x:xs) n 1 
  where
       dropEvery' (x:xs) n i = (if (n `divides` i) then [] else [x])++ (dropEvery' xs n (i+1))
       dropEvery' [] _ _ = []
       divides x y = y `mod` x == 0

dropEvery2 :: [a] -> Int -> [a]
dropEvery2 xs n = dropEvery' xs n 1 
  where
       dropEvery' (x:xs) n i = (if (n `divides` i) then [] else [x])++ (dropEvery' xs n (i+1))
       dropEvery' [] _ _ = []
       divides x y = y `mod` x == 0

theyAreSame xs n = (dropEvery xs n) == (dropEvery2 xs n)
propTheyAreSame xs n = n > 0 ==> theyAreSame xs n

在 ghci 中你可以做

*Main> quickCheck propTheyAreSame 
+++ OK, passed 100 tests.

我还手动测试了一些角落案例

*Main> dropEvery [] 0
[]
*Main> dropEvery2 [] 0
[]
*Main> dropEvery [] undefined
[]
*Main> dropEvery2 [] undefined
[]

所以他们看起来是一样的。

所以我们的学习成果:

  1. 快速检查非常适合这种东西
  2. 不要低估自己。:)
于 2013-04-27T16:45:57.990 回答