Closures (in Haskell)

后端 未结 2 1584
余生分开走
余生分开走 2021-02-01 07:43

To me a Closure is a (nested?) function with co-located data.

When you write software in Haskell and look it through afterwards, you frequently find closures that you h

相关标签:
2条回答
  • 2021-02-01 08:20

    In Haskell, functions are an essential part of the language, largely because Haskell is based on the Lambda Calculus.

    In the Lambda Calculus, there are functions that have "free variables", meaning that they use variables that were not passed as direct parameters to them. Functions with free variables are what you would call "closures" in this case.

    Because functions with free variables are so common in LC, they also form an integral part of the Haskell language. For example, when you write this:

    f a b c = a * b + c
    

    ... you could also be writing this, with the exact same result:

    f a b = \ c -> a * b + c
    

    ... or even:

    f a b = let product = a * b in \ c -> product + c
    

    ... further equivalent changes:

    f a = \ b -> let product = a * b in \ c -> product + c
    

    This is because Haskell essentially creates functions with free variables everywhere, and thus, closures are created all the time. Some of these might be optimized away by the compiler, but it is safe to assume that there will be more closures used than you might ever be able to discover on your own.

    So, don't try to locate closures; they are nothing special in Haskell and are used all the time.

    0 讨论(0)
  • 2021-02-01 08:36

    Typically, if I need to precompute tables or something for a function, or there's a function that requires a lot of data, yeah, that'll be done as a closure. For example, on my AI homework the other day, I wrote a thing that learned from a lot of samples and then popped out a (Point -> Bool) function, but that function had to depend on a lot of data that I'd accumulated from the learning process.

    0 讨论(0)
提交回复
热议问题