Multilingualism and MATLAB
Thanks to Numerical Analysis, this quarter’s big new language will turn out to be one not often mentioned by “pure” computer scientists: MATLAB. Starting yesterday, I was tasked with writing a number of small functions to do things like estimate function zeros and values of irrational numbers by a variety of methods (bisection, secant, Newton’s, etc.).
Naturally, wanting these estimations to be as flexible as possible (and seeing the book request Newton’s method applied to several functions in series), I immediately tried to design the estimation function to accept another function as an argument to be evaluated later. In a language with first-class functions, this would be trivial; MATLAB, unfortunately, is not such a language.
Even more unfortunately, I tried several times to find MATLAB first-class functions, or any way to pass a function to another function. Eventually, I stumbled across the answer: function handles.
Essentially, passing MATLAB functions doesn’t promote those functions to first-class citizens; instead, it uses a more C-like approach and gives you a “handle” on the function, much in the way a function pointer might. “Function handle” is a data type in MATLAB, though, so it’s a bit more explicitly defined than C pointers. In addition, handles let you do fun things like declare anonymous functions, which is all but impossible in C.
Take for example this nifty MATLAB definition for an explicit “square” function:
sq = @(x) x^2
Given another function that accepts a handle as an argument, the programmer can then just pass sq
as the argument, then within the called function evaluate something like sq(3)
and come out with 9, just as expected.
A lot of programmers (myself included) tend to get thrown by this kind of stuff when first encountering a new language. Try to remember not to force one language into the mold of another, or demand features that may simply not be present; instead, grow into the language, picking up idiomatic expressions and design as appropriate while still relating core concepts back to known ideas from other languages.