gpt4 book ai didi

haskell - 从列表中删除第 n 个元素

转载 作者:行者123 更新时间:2023-12-02 17:21:10 25 4
gpt4 key购买 nike

我自学 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

谁能帮我解决这个问题吗?

最佳答案

我认为它们是相同的,作者可以按照您的建议简化代码。无论如何,我尝试了两个版本 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. Quickcheck 非常适合此类内容
  2. 不要低估自己。 :)

关于haskell - 从列表中删除第 n 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16254478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com