Haskell-这是关闭吗? [英] Haskell - is this a closure?
问题描述
有一段源代码源于对我的另一个问题,
infFromPrefix :: Eq a => ([a] -> [a]) -> [a] -> [a]
infFromPrefix rules prefix = inf where
inf = prefix ++ case stripPrefix prefix (rules inf) of
Just suffix -> suffix
Nothing -> error "Substitution does not preserve prefix"
我很确定 inf
必须是一个闭包,因为它可以使用其传递给 infFromPrefix
的参数来访问其封闭范围内的变量,但是不确定本质上 infFromPrefix
和 inf
是相同的函数, inf
只允许
a更简洁的定义。等效的定义为
where I am pretty sure that inf
must be a closure as it has access to variables from its enclosing scope in the sense that it uses the parameters passed to infFromPrefix
, but am unsure since essentially infFromPrefix
and inf
is the same function, the inf
only allows
a more succinct definition. An equivalent definition would be
infFromPrefix rules prefix = prefix ++ case stripPrefix prefix (rules $ infFromPrefix rules prefix) of
Just suffix -> suffix
Nothing -> error "Substitution does not preserve prefix"
我正确,是 inf
关闭?
推荐答案
基于Wiki文章编程中的关闭,我认为可以说 inf
是确实不是闭包:
Based on the Wiki article on Closures in programming, I think it can be said that inf
is indeed not a closure:
请特别注意,嵌套函数定义本身不是闭包:它们具有自由变量,尚未绑定。只有在使用参数的值对封闭函数进行求值后,嵌套函数绑定的自由变量才会创建闭包,然后从封闭函数中返回闭包。
Note especially that the nested function definitions are not themselves closures: they have a free variable, which is not yet bound. Only once the enclosing function is evaluated with a value for the parameter is the free variable of the nested function bound, creating a closure, which is then returned from the enclosing function.
这篇关于Haskell-这是关闭吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!