为什么我的函数 dropR(Prelude drop 的逆函数)看起来像它的样子?

Lum*_*nar 2 haskell function haskell-prelude

我对编程和练习编写函数还是新手,我试图扭转 Prelude 掉落的影响;

drop :: Int -> [a] -> [a]
drop 0 [] = []
drop 0 (x:xs) = x:xs
drop n [] = []
drop n (x:xs) = drop (n-1) xs
Run Code Online (Sandbox Code Playgroud)

变成了我最初命名为 dropR 的东西。

dropR :: Int -> [a] -> [a] -- drops from the right of the list
dropR 0 [] = []
dropR 0 (x:xs) = x:xs
dropR n [] = []
dropR n (x:xs) = reverse (drop (n-1) (reverse xs ++ [x]))
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不起作用,因为dropR 2 [1,2,3,4,5]返回的输入[1,2,3,4]并不[1,2,3]像我希望的那样。使用 drop 2,我会在列表中获得 3 个值,而不是 4 个。我将函数更改为;

dropR :: Int -> [a] -> [a] -- drops from the right of the list
dropR 0 [] = []
dropR 0 (x:xs) = x:xs
dropR n [] = []
dropR n (x:xs) = reverse (drop n (reverse xs ++ [x]))
Run Code Online (Sandbox Code Playgroud)

它按照我想要的方式工作,但我不明白为什么第一个不起作用。我认为它只会反转列表并获取与常规下降相同数量的值,然后我就可以反转它。

为什么 drop 需要drop (n-1)而我的 dropR 只需要drop n?发生这种情况是因为 drop 中的递归而不是 dropR 中的递归吗?

Fyo*_*kin 5

让我们看一个例子:

dropR 2 [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

在您的第一次尝试中,最后一行匹配,其中:

  • n = 2
  • x = 1
  • xs = [2, 3, 4]

所以:

  • reverse xs = [4, 3, 2]
  • reverse xs ++ [x] = [4, 3, 2, 1]
  • drop (n-1) (reverse xs ++ [x]) = drop 1 [4, 3, 2, 1] = [3, 2, 1]
  • reverse (drop (n-1) (reverse xs ++ [x])) = [1, 2, 3]
  • 量子电动力学

另一方面,在你的第二次尝试中:

  • reverse xs = [4, 3, 2]
  • reverse xs ++ [x] = [4, 3, 2, 1]
  • drop n (reverse xs ++ [x]) = drop 2 [4, 3, 2, 1] = [2, 1]
  • reverse (drop (n-1) (reverse xs ++ [x])) = [1, 2]
  • 量子电动力学

但更深入地了解一下。

观察这reverse xs ++ [x]实际上是一样的reverse (x:xs):你反转尾巴,然后将头部粘在它的末端。这与首先​​反转整个列表相同。

所以你真正要做的是:

  • 颠倒整个列表
  • n从它掉下来
  • 再次扭转它

因此,您不妨删除那里的所有案例,然后执行以下操作:

dropR n xs = reverse (drop n (reverse xs))
Run Code Online (Sandbox Code Playgroud)

或者更短一点:

dropR n = reverse . drop n . reverse
Run Code Online (Sandbox Code Playgroud)

我认为这个变体稍微好一些,因为它更清楚地表达了这个想法:反转,然后 drop n,然后再次反转。