Functions as Values

The usefulness of lambdas becomes apparent when we combine two ideas:

  • Lambdas are values just like Strings, Objects, and Booleans
  • Values can be passed to functions as arguments, as well as returned from functions.

In other words, lambdas become useful when you want to pass functions as arguments to other functions, or return a function from a function.

Here’s an example of using a HOF, filter, to make sure an Array only contains odd numbers:

DW Script:

%dw 2.0
output json

fun isOddNum(n) =
  (n mod 2) == 1

// Generate [1, 2, ..., 5]
var numbers = (1 to 5)
---
filter(numbers, (n, idx) -> isOddNum(n))

Output:

[1,3,5]

The filter function takes two arguments, an Array and a Lambda. In situations like these, it’s important to specify what the lambda should do as well. In the case of filter, the lambda should take in two arguments: an item in the Array, and the index of that particular item. It should return a Boolean. This Boolean value is used to determine if a value should be in the returned Array or not. It is the responsibility of the receiving function to pass arguments into the lambda you specified, and do something with the return value.

We had to give a name to the function (isOddNum) in order to use it, even though we were never going to use it again. This is exactly where lambdas come in. They enable us to pass functions to other functions without the inconvenience of having to think up a name for them:


DW Script:

%dw 2.0
output json

var numbers = (1 to 5)
---
filter(numbers, (n, idx) -> (n mod 2) == 1)

Output:

[1,3,5]

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

Instagram

Facebook

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago