gpt4 book ai didi

Haskell 语法 : what does drop (n+1) [] = [] mean?

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

(n+1) 是什么意思?我知道两者都是递归 Haskell 函数并且都使用模式匹配。

我不明白它将如何模式匹配 factorial (n+1) 以及 factorial 右侧的 (n+1) =.

使用drop函数,为什么会drop 0 xs = xs?那么 drop (n+1) [] = [] 又如何呢?

--Example 1
factorial 0 = 1
factorial (n+1) = (n+1) * factorial n

--Example 2
drop :: Int -> [a] -> [a]
drop 0 xs = xs
drop (n+1) [] = []
drop (n+1) (_:xs) = drop n xs

顺便说一句,我在编译时遇到错误。

  • 代码编译失败
  • 模式解析错误:n + 1

更新:感谢您向我指出正确的术语。我找到了这个n+k patterns 。由于自 2010 年以来 n+k 模式已被删除,我还在 how to enable this pattern 上发现了这个问题.

最佳答案

这些是NPlusKPatterns ,已于 2010 年从该语言中删除,现在仅适用于上述语言扩展。

n + k - 模式

drop (n+1) [] = []

绑定(bind)n参数值减一,前提是参数值为 >= 1 。该模式与参数 <= 0 不匹配.

如果

drop :: Int -> [a] -> [a]
drop 0 xs = xs
drop (n+1) [] = []
drop (n+1) (_:xs) = drop n xs

用负号 Int 调用论证,例如

drop (-2) "foo"

没有模式匹配,你会得到一个异常。

一般来说,如果你定义(举一个愚蠢的例子)

foo :: Int -> Int
foo (n+5) = 3*n
foo (n+2) = n
foo (n+1) = 2*n

如果您调用foo 7 ,第一个模式匹配和 n将绑定(bind)到2 ,所以foo 7 = 6 。如果您调用foo 3 ,第一个模式不匹配 ( 3-5 = -2 < 0 ),但第二个模式匹配,并且绑定(bind) n3-2 = 1 ,因此foo 3 = 1 。如果您调用foo 1 ,前两个模式都不匹配,但最后一个匹配,然后 n绑定(bind)到1 - 1 = 0 ,所以foo 1 = 0 。调用foo有一个参数< 1引发异常。

And with drop function why is it drop 0 xs = xs? And what about drop (n+1) [] = []?

嗯,drop 0从列表前面删除 0 个元素,因此它根本不会更改列表参数。并且您无法从空列表中删除元素,因此 drop (n+1) [] = []这是除了引发错误之外您唯一能做的事情。

关于Haskell 语法 : what does drop (n+1) [] = [] mean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17318651/

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