All Products
Search
Document Center

MaxCompute:Lambda functions

Last Updated:Sep 04, 2023

Lambda functions are anonymous functions that do not need to be named and can be used as parameters in other functions or methods. This topic describes the limits, syntax, and examples of Lambda functions.

Limits

  • Subqueries, such as x->2+(SELECT3), are not supported.

  • Aggregate operations, such as x -> max(y), are not supported.

Syntax

Syntax: Parameter list -> Expression or code block.

  • Parameter list: a list of parameters that are received by the Lambda function. The parameter list can be empty or contains one or more parameters.

  • ->: a delimiter that is used to separate a parameter list from an expression or code block.

Examples

  • Example 1: Obtain the squared value of an array column.

    SELECT numbers,transform(numbers, n -> n * n) as squared_numbers
    FROM (
        VALUES (ARRAY(1, 2)),(ARRAY(3, 4)),(ARRAY(5, 6, 7))
    ) AS t(numbers);

    The following result is returned:

    +------------+-----------------+
    | numbers    | squared_numbers |
    +------------+-----------------+
    | [5,6,7]    | [25,36,49]      |
    | [3,4]      | [9,16]          |
    | [1,2]      | [1,4]           |
    +------------+-----------------+
  • Example 2: Convert an array into a string.

    SELECT transform(prices, n -> CAST(n AS STRING ) || '$') as price_tags
    FROM (
        VALUES
            (ARRAY(100, 200)),(ARRAY(30, 4))
    ) AS t(prices);

    The following result is returned:

    +------------+
    | price_tags |
    +------------+
    | ["30$","4$"] |
    | ["100$","200$"] |
    +------------+
  • Example 3: Calculate the value of a linear function.

    SELECT xvalues, a, b,
           transform(xvalues, x -> a * x + b) as linear_function_values
    FROM (
        VALUES (ARRAY(1, 2), 10, 5),(ARRAY(3, 4), 4, 2)
    ) AS t(xvalues, a, b);

    The following result is returned:

    +------------+------------+------------+------------------------+
    | xvalues    | a          | b          | linear_function_values |
    +------------+------------+------------+------------------------+
    | [3,4]      | 4          | 2          | [14,18]                |
    | [1,2]      | 10         | 5          | [15,25]                |
    +------------+------------+------------+------------------------+