Quantcast
Viewing all articles
Browse latest Browse all 1449

[VBA] Lambda Syntax - No script control or cheats! Happy for ports to VB6

Lambda Expressions

I've already posted this library elsewhere but figured that people on VBForums would find it useful too! This is currently only written to work in VBA but I believe a port to VB6 would only require the alteration of a few declarations. Or perhaps in quite a few within evaluateFunc... Happy to have pull requests if anyone wants to make it usable in VB6!

What is a lambda expression?

A lambda expression/anonymous function is a function definition that is not bound to a name. Lambda expressions are usually "1st class citezens" which means they can be passed to other functions for evaluation.

I personally believe this is best described with an example. Imagine we wanted to sort an array of sheets by their name. In VBA this would be relatively complex and require an understanding of how to sort data in the first place, as well as which algorithms to use. Lambda allows us to define 1 sorting function and then provide our lambda function to provide the ID to sort on:

Example.bas Code:
  1. Sub Main
  2.     myArray = Array(Sheets(1),Sheets(2))
  3.     newArray = sort(myArray, stdLambda.Create("$1.name"))
  4. End Sub
  5.  
  6. Function sort(array as variant, accessor as stdICallable)
  7.     '... sorting code ...
  8.        elementID = accessor(element)
  9.     '... sorting code ...
  10. End Function

Download

The file can be found on github here:
stdLambda.cls.

stdICallable will also be required: stdICallable.cls

How to use stdLambda

The Create() constructor is the main way to create an instance of the stdLambda object.

Example.bas Code:
  1. Sub test()
  2.     Dim cb as stdLambda
  3.     set cb = stdLambda.Create("1+1")
  4. End Sub

To define a function which takes multiple arguments $# should be used where # is the index of the argument. E.G. $1 is the first argument, $2 is the 2nd argument and $n is the nth argument.

Example.bas Code:
  1. Sub test()
  2.     Dim average as stdLambda
  3.     set average = stdLambda.Create("($1+$2)/2")
  4. End Sub

You can also define functions which call members of objects. Use xxx#xxx() to call functions and xxx.xxx() to call properties.

Example.bas Code:
  1. Sub test()
  2.     Debug.Print stdLambda.Create("$1.Name")(someObject)  'returns ThisWorkbook.Name
  3.     Call stdLambda.Create("$1#Save")(someObject)         'calls ThisWorkbook.Save
  4. End Sub

The lambda syntax comes with many VBA functions which you are already used to...

Example.bas Code:
  1. Sub test()
  2.     Debug.Print stdLambda.Create("Mid($1,1,5)")("hello world")        'returns "hello"
  3.     Debug.Print stdLambda.Create("$1 like ""hello*""")("hello world") 'returns true
  4. End Sub

As well as an inline if statement:

Example.bas Code:
  1. Sub test()
  2.     Debug.Print stdLambda.Create("if $1 then 1 else 2")(true)        'returns 1
  3.     Debug.Print stdLambda.Create("if $1 then 1 else 2")(false)       'returns 2
  4.  
  5.     'Note: this will only call someObj.CallMethod() and will not call someObj.CallMethod2() (unless 1st arg is supplied as false of course)
  6.     Debug.Print stdLambda.Create("if $1 then $2#CallMethod() else $2#CallMethod2()")(true,someObj)
  7. End Sub

With stdLambda you are not limited to a single lines, you can also use multiple lines. Note the result of the last line in the lambda is returned:

Example.bas Code:
  1. Call stdLambda.Create("2+2: 5*2").Run()
  2.  
  3. '... or ...
  4.  
  5. Call stdLambda.CreateMultiline(array( _
  6.   "2+2", _
  7.   "5*2", _
  8. )).Run()

You can also use variables, much like in VB6:

Example.bas Code:
  1. 'the last assignment is redundant, just used to show that assignments result in their value
  2. Debug.Print stdLambda.CreateMultiline(array( _
  3.   "count = $1", _
  4.   "footPrint = count * 2 ^ count" _
  5. )).Run(2) ' -> 8

Finally you can use Function definitions if you want to use recursion:

Example.bas Code:
  1. stdLambda.CreateMultiline(Array( _
  2.   "fun fib(v)", _
  3.   "  if v<=1 then", _
  4.   "    v", _
  5.   "  else ", _
  6.   "    fib(v-2) + fib(v-1)", _
  7.   "  end", _
  8.   "end", _
  9.   "fib($1)" _
  10. )).Run(20) '->6765

Evaluating lambdas

Use default member execution:

Example.bas Code:
  1. Sub test()
  2.     Dim average as stdLambda
  3.     set average = stdLambda.Create("($1+$2)/2")
  4.     Debug.Print average(1,2)   '1.5
  5. End Sub

Use Run method:

Example.bas Code:
  1. Sub test()
  2.     Dim average as stdLambda
  3.     set average = stdLambda.Create("($1+$2)/2")
  4.     Debug.Print average.Run(1,2)   '1.5
  5. End Sub

Use RunEx method, supplying an array of arguments:

Example.bas Code:
  1. Sub test()
  2.     Dim average as stdLambda
  3.     set average = stdLambda.Create("($1+$2)/2")
  4.     Debug.Print average.RunEx(Array(1,2))   '1.5
  5. End Sub

Sometimes it's useful to use an interface. In this case use stdICallable interface:

Example.bas Code:
  1. Sub test(ByVal func as stdICallable)
  2.     func.Run(ThisWorkbook, 1, "hello world")
  3. End Sub

An update as of 16/09/2020 added the Bind() method to stdLambda as well. The Bind() method creates a new ICallable that, when called, supplies the given sequence of arguments preceding any provided when the new function is called. This ultimately saves on expression compilation time.

Example.bas Code:
  1. 'Expression created, argument bound.
  2. Dim cb as stdLambda: set cb = stdLambda.Create("$1 + $2").Bind(5)
  3. Debug.Print cb(1) '6
  4. Debug.Print cb(2) '7
  5. Debug.Print cb(3) '8
  6.  
  7. 'No compilation required, cached lambda is used with new bound argument
  8. set cb = stdLambda.Create("$1 + $2").Bind(6)
  9. Debug.Print cb(1) '7
  10. Debug.Print cb(2) '8
  11. Debug.Print cb(3) '9

How it works

Finally, how does the class work internally?

Create first looks to see if a lambda already exists, if it does it is returned, else it calls Init which:
  • Tokenises the string using Regex
  • Calls parseBlock() which uses a top-down parsing algorithm to parse the entire block to an array/stack containing operations (i.e. compiles to byte code)


Then when an expression is executed, Run calls evaluate which:

  • Loops over all operations, detects the type and subtype of the operation
  • Performs the operations function
  • After all operations have executed the 1st item in the stack is returned.


Integration with the STD-VBA Library

Thought i'd give a taste of one of the core reasons I built this library!

Example.bas Code:
  1. 'Create an array
  2. Dim arr as stdArray
  3. set arr = stdArray.Create(1,2,3,4,5,6,7,8,9,10) 'Can also call CreateFromArray
  4.  
  5. 'More advanced behaviour when including callbacks! And VBA Lamdas!!
  6. Debug.Print arr.Map(stdLambda.Create("$1+1")).join          '2,3,4,5,6,7,8,9,10,11
  7. Debug.Print arr.Reduce(stdLambda.Create("$1+$2"))           '55 ' I.E. Calculate the sum
  8. Debug.Print arr.Reduce(stdLambda.Create("Max($1,$2)"))      '10 ' I.E. Calculate the maximum
  9. Debug.Print arr.Filter(stdLambda.Create("$1>=5")).join      '5,6,7,8,9,10
  10.  
  11. 'Execute property accessors with Lambda syntax
  12. Debug.Print arr.Map(stdLambda.Create("ThisWorkbook.Sheets($1)")) _
  13.                .Map(stdLambda.Create("$1.Name")).join(",")            'Sheet1,Sheet2,Sheet3,...,Sheet10
  14.  
  15. 'Execute methods with lambda:
  16. Call stdArray.Create(Workbooks(1),Workbooks(2)).forEach(stdLambda.Create("$1#Save")
  17.  
  18. 'Sort objects by date, and then print names concatenated with comma
  19. Debug.Print stdArray.Create(ObjA,ObjB,ObjC,ObjD,ObjE).sort(stdLambda.Create("$1.Date")).map(stdLambda.Create("$1.Name")).join(",")
  20.  
  21. 'We even have if statement!
  22. With stdLambda.Create("if $1 then ""lisa"" else ""bart""")
  23.   Debug.Print .Run(true)                                              'lisa
  24.   Debug.Print .Run(false)                                             'bart
  25. End With


Long term goals

The intermediate representation is good, but it would be even better if we could compile to machine code... I'm pretty sure this is even more difficult, but in the pursuit of speed that's maybe where we'll have to go!

Happy Coding!
~Sancarn

Viewing all articles
Browse latest Browse all 1449

Trending Articles