Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - is this a closure?

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?

like image 358
Filip Allberg Avatar asked Oct 23 '15 15:10

Filip Allberg


People also ask

Does Haskell have closure?

Functions with free variables are what you would call "closures" in this case. This is because Haskell essentially creates functions with free variables everywhere, and thus, closures are created all the time.

What is a closure in Haskell?

The function \y -> x + y has a bound variable y and a free variable x. A closure is a function with a free variable that takes its value from the surrounding environment. The function returned by add x is a closure, since it carries around the value of x .

What is closure with example?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.

Are closures pure functions?

No, closures do not cause a function to be impure, as long as the closed value is constant (neither changed by the closure nor other code), which is the usual case in functional programming.


1 Answers

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.

like image 166
Roman Cheplyaka Avatar answered Sep 19 '22 08:09

Roman Cheplyaka