MS Excel: Functions are first-class objects
What makes a function a first-class object?
This is almost certainly an advanced discussion. And, we will start with a short introduction to what makes a first-class object. As the phrase implies, a language (or a programming platform) considers a function as a first-class object if it treats a function on par with other objects such as an array or a list. This means
The 2 sections below address how Excel treats functions as first-class objects and how Python does the same.
Excel's functions, particularly the LAMBDA function
Modern Excel's functions are first-class objects. The LAMBDA function in particular, with the help of the LET function, satisfies all of the above requirements.
=LET(x,LAMBDA(n,SUM(n)),
? ? x(SEQUENCE(9))
? ? )
=LET(x,LAMBDA(f,n,f(n)),
? ? _sum,LAMBDA(n,SUM(n)),
? ? x(_sum,SEQUENCE(9)))
=LET( _sum,LAMBDA(n,SUM(n)),
? ? _mult,LAMBDA(n,PRODUCT(n)),
? ? _chooser, IF(RAND()<0.5,_sum,_mult),
? ? _chooser(SEQUENCE(9)))
An alternative formulation, which some might find easier to understand, is below:
=LET(_choice,RAND(),_n,SEQUENCE(9),
? ? _caller,LAMBDA(f,n,f(n)),
? ? _sum,LAMBDA(n,SUM(n)),
? ? _mult,LAMBDA(n,PRODUCT(n)),
? ? _caller(IF(_choice<0.5,_sum,_mult),_n))
Functions as objects in Python
The above treatment of functions in Excel is similar to how other languages such as Python or JavaScript treat functions. In this section, we see how Python treats functions as objects - JavaScript has similar constructs. That means:
领英推荐
def f(o)
? ? return(sum(o))
g=f
print(f(range(10)))
print(g(range(10))):
Subsequent examples refer to 2 Python functions. The first sums the values in a list, and the second multiplies the values.
def _sum(l):
? ? return(sum(l))
def mult(l):
? ? from functools import reduce
? ? return(reduce(lambda a,b:a*b,l))
def g(o,l):
? ? return(o(l))
We would use it as
print(g(_sum,range(10)))
print(g(mult, range(1,10)))
def _choose():
? ? from numpy import random
? ? return(_sum if random.random()<0.5 else mult)
and we would use it as below. Half of the time we will see 45, the other half 362880
print(_choose()(range(1,10)))
Essentially, there is no difference between how we treat an object like a list and a function.
Summary
With the recent enhancements to Excel's functions, Excel is a first-class programming platform - it is Turing complete. What that means is that we can do any computation in Excel by itself! The article explained how functions are now first-class objects in Excel, laying the foundation for more sophisticated analytics involving, say, recursive functions.
Have you explored modern Excel's functions? Share your ideas and thoughts on how Microsoft has changed Excel with dynamic array formulas, spill arrays, and related functions.
My previous post: Generate unique random integers