Haskell - is this a closure?

我是研究僧i 提交于 2020-01-24 03:10:33

问题


There is a piece of source-code that originated in an answer to another one of my questions,

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"

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"

Am I correct, is inf a closure?


回答1:


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.




回答2:


I would agree with Lennart and Daniel that closure is an implementation-specific term and is not something well-defined in general. Moreover, I don't hear Haskellers talk about closures a lot outside of the implementation issues; when programmers in other languages casually talk about "closures", they usually mean what we call "lambdas". (As in "does that language have closures?".)

Anyway, let's talk about GHC.

GHC (or, more precisely, STG) calls a closure any heap object that is not a constructor application.

(In case you think this is a broad definition, compare this with the original STG paper where even constructors were called closures.)

Your inf is certainly an STG closure; it is a thunk that will be allocated on the heap and returned to the caller.



来源:https://stackoverflow.com/questions/33305935/haskell-is-this-a-closure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!