【发布时间】:2014-03-16 10:07:52
【问题描述】:
为什么这些伪 Haskell 函数定义不被接受?
f n = if n<3 then n else g 2 2 1 0 where
g n a b c = a -- note that 'n' is a value of the enclosing scope
g k a b c = g (k+1) (a+2*b+3*c) a b
计算这个“运动函数”:f(n) = n if n<3 else f(n-1) + 2*f(n-2) + 3*f(n-3)
fib n = let
f n a b = b -- note that 'n' is a value of the enclosing scope
f k a b = f (k+1) b (a+b)
in f 1 0 1
用于计算斐波那契数。当然可以:
fib n = let { f k a b = if k==n then b else f (k+1) b (a+b);} in f 1 0 1
但是在where 的示例和let 的示例中,我都明白了
Warning: Pattern match(es) are overlapped
为什么我不能使用与从封闭范围获得的值匹配的模式来定义函数闭包?
这是因为封闭范围的值是在运行时(通常)确定的,并且由于某种原因(什么原因?)编译器无法编排?
【问题讨论】:
-
这是可能的,但它是一个相当脆弱的结构,根据它是否已经被绑定,在一个模式中有 n 表示不同的东西。
-
我不确定你在问什么。
n在您的示例中可用于g...只要您不调用gs 参数之一n。
标签: haskell scope pattern-matching closures