Jef*_*eff 2 syntax haskell functional-programming
什么(n+1)意思?我知道它们都是递归的Haskell函数,并且正在使用模式匹配.
我不明白它的模式匹配factorial (n+1)以及(n+1)RHS的模式匹配factorial =.
而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
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我在编译时遇到错误.
更新:感谢您指出正确的术语.我发现了这个n + k模式.由于自2010年以来已经删除了n + k个模式,我还发现了关于如何启用此模式的问题.
这些是NPlusKPatterns在2010年从语言中删除的,现在只有提到的语言扩展名才可用.
- n + k模式
drop (n+1) [] = []
Run Code Online (Sandbox Code Playgroud)
n如果参数值为,则绑定参数值减1 >= 1.该模式与参数不匹配<= 0.
因此,如果
drop :: Int -> [a] -> [a]
drop 0 xs = xs
drop (n+1) [] = []
drop (n+1) (_:xs) = drop n xs
Run Code Online (Sandbox Code Playgroud)
用负Int参数调用,比如
drop (-2) "foo"
Run Code Online (Sandbox Code Playgroud)
没有模式匹配,你得到一个例外.
通常,如果你定义(对于一个愚蠢的例子)
foo :: Int -> Int
foo (n+5) = 3*n
foo (n+2) = n
foo (n+1) = 2*n
Run Code Online (Sandbox Code Playgroud)
if you call foo 7, the first pattern matches and n will be bound to 2, so foo 7 = 6. If you call foo 3, the first pattern doesn't match (3-5 = -2 < 0), but the second does, and that binds n to 3-2 = 1, hence foo 3 = 1. If you call foo 1, neither of the first two patterns matches, but the last does, and then n is bound to 1 - 1 = 0, so foo 1 = 0. Calling foo with an argument < 1 raises an exception.
And with drop function why is it
drop 0 xs = xs? And what aboutdrop (n+1) [] = []?
Well, drop 0 drops 0 elements from the front of the list, so it doesn't change the list argument at all. And you can't drop elements from an empty list, so drop (n+1) [] = [] is the only thing you can do except raising an error.
这是一种所谓的n+k模式.该模式(n+1)匹配任何正整数,并给出n该整数的值减1.所以如果你调用drop 1 xs的值n将为0.
为什么
drop 0 xs = xs
因为如果从列表中删除0个元素,最终会得到相同的列表.
那怎么样
drop (n+1) [] = []?
这就是说,如果从空列表中删除任意数量的项目,最终会得到一个仍为空的列表.除了失败的错误信息之外,在这种情况下,这确实是唯一明智的做法.