Comp 110 Function Literals

Function Literals

Function literals are useful where function parameters are required. Often, this is helpful with filter, map, and reduce. It is especially nice if we only need to use that function once and we aren't planning on reusing the same logic again. Instead of making a function then passing the name of the function as our argument, we just pass the logic directly.

Here's an example with lists and the filter function that does NOT use function literals:

let a: List<number> = listify(1, 12, 123, 1.234);
 
let greaterThan10 = (n: number): boolean => {
      return n > 10;
};
 
let b: List<number> = filter(a, greaterThan10);
 
print(b); // prints the list 12->123->null

Here's the same example using function literals:

let a: List<number> = listify(1, 12, 123, 1.234);
 
let b: List<number> = filter(a, (n: number): boolean => {
      return n > 10;
});
 
print(b); // prints the list 12->123->null

In this last version of the example, we just plugged the function right in as our argument, and we still got the same result as in the previous version when we stored it as greaterThan10 and passed in greaterThan10 as the argument. Here we used it with filter, but it's also nice with map and reduce.

Type Inference and Function Parameters

When using function literals as part of a higher order function, we can rely on type inference for its parameter types and return types. Since we can do this, we can go ahead and remove these types when we use function literals in this way. Here's how this would look with the previous example:

// we'll also go ahead and rely on type inference in our declarations of a and b
let a = listify(1, 12, 123, 1.234);
 
let b = filter(a, (n) => {
      return n > 10;
});
 
print(b); // prints the list 12->123->null

When doing this, we can use a shorthand notation, since these kinds of function literals contain only one return statement. There are three steps to this:

  1. drop the curly braces
  2. drop the return keyword
  3. drop the semicolon after the return statement's expression

Here's what this becomes in our example:

let a = listify(1, 12, 123, 1.234);
 
let b = filter(a, (n) => n > 10);
 
print(b); // prints the list 12->123->null