Am I right in thinking that Xojo doesn’t support closures?
I ask because I am currently neck deep in my compiler trying to implement them and it suddenly occurred to me that I might not need to bother. After all, Xojo as a language has done pretty well without them.
Lambdas or Anonymous functions are a kind of function used as parameter for a high order function. A Closure is a function with “bound” variable values that can be passed around. A Closure is a Lambda, a Lambda is not necessarily a Closure (need to have bound values).
So in a pseudo-Xojo, you could do things like:
Function MyFun( f As Function(x As Integer, y As Integer) As Double, s As String)
Msgbox s + f(x,y).ToString
MyFun( (10, 20) (
Dim n As Integer = x*y
Dim r As Double = n / 10
Return r ), "This is x*y/10")
MyFun( (11, 21) (
Dim n As Integer = x+y
Dim r As Double = n / 11
Return r ), "This is x+y/11")
Function GetAClosure(lim As Integer) As Function // lim will be bound to the resulting function
Return Function(x As Integer -> (If x<lim Then Msgbox "true")) // Function() is value, Function()() is call
Dim LessT10 As Function = GetAClosure(10)
Dim LessT20 As Function = GetAClosure(20)
LessT10(5) // true
LessT20(5) // true
LessT20(10) // true
LessT20(15) // true
Thanks for the further clarification @Rick.A. I’ve decided against implementing them in my language - honestly it mostly because I never use them and I can’t be arsed to rip up the pretty fast stack-based local variable lookup my VM currently uses to shoehorn in heap-managed locals which closures would necessitate.
It is very useful for some contexts. You can think as storing a function in a variable and passing around to be used by some other process. Imagine that you have a task like sorting things in some unusual way besides ascending and descending in alphabetic order, so instead of writing many sorting functions, you can write a “generic” function to sort data and one parameter is a function to classify if a<b in some unusual way. You could store one way as Dim sortAsc As Function… Dim sortDesc As Function… Dim sortInsane As Function… and pass those “names” as a parameter to the sort routine. Small expressions can be written just in place like myArray.sort((x,y)->(x<y))