Is Haskell a closure?

There is a piece of source code that came up in response to another 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 sure that inf should be a closure, because it has access to variables from its scope in the sense that it uses the parameters passed to infFromPrefix , but not sure, since essentially infFromPrefix and inf are the same function, inf allows only more concise 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" 

Is inf shorting correct?

+7
closures haskell
source share
2 answers

Based on the Wiki article on Closures in programming , I think we can say that inf really not a closure:

Note that the definitions of nested functions themselves are not private: they have a free variable that is not yet bound. Only after the evaluating function is evaluated with the value for the parameter is a free variable of the nested function creating a closure, which is then returned from the closing function.

+4
source share

I agree with Lennart and Daniel that closure is a specific implementation term and is not something specific in general. Moreover, I donโ€™t hear how the Haskellers talk a lot about closure outside implementation problems; when programmers in other languages โ€‹โ€‹speak casually about closures, they usually mean what we call lambdas. (Like in "Does this language have closures?".)

In any case, let me talk about the GHC.

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

(If you think this is a broad definition, compare it to the original STG paper, where even constructors are called closures.)

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

+10
source share

All Articles