【发布时间】:2013-04-27 16:34:51
【问题描述】:
我已经自学了一个月左右的 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
谁能帮我解决这个问题?
【问题讨论】:
-
注意这个函数的参数顺序是“错误的”;像这样的函数通常是
Int -> [a] -> [a],这通常对管道情况更有用。为什么他们在那个例子中反其道而行之,我不知道。
标签: haskell