Skip to main content

AML Function

caution

AML Function cannot return models and datasets for now due to internal technical limitations. You can use AML Extend to reuse models and datasets instead.

Introduction

An AML function is a reusable block of code designed to perform a specific task. It takes inputs (called parameters), processes them, and returns an output.

Syntax

Func <function-name>((<param>(: <param_type>)?)*) (=> <return_type>) {
<function_body_block>
}
  • The return type is optional as most of the time it can be inferred
  • The last expression will be returned as the output, there is no explicit return keyword

Function declarations

Func sum(x: Number, y: Number) {
x + y
}

Func double(x: Number) {
const multiple = 2
x * multiple
}

Func myvizBlockWithDataset(dataset: String) { // auto infer return type = VizBlock
VizBlock {
label: 'A pie chart'
viz: PieChart {
dataset: dataset // use the dataset parameter here instead of hard-coding
legend: ref('public_users', 'role')
series {
field {
ref: ref('public_users', 'id')
aggregation: 'sum'
}
}
}
}
}

// equivalent to
Func myvizBlockWithDataset(dataset: String) => VizBlock { // explicitly declare return type
VizBlock {
...
}
}

Calling functions

A function will be executed when it is called:

myvizBlockWithDataset('ecommerce')

// return value

/*
VizBlock {
label: 'A pie chart'
viz: PieChart {
dataset: 'ecommerce'
legend: ref('public_users', 'role')
series {
field {
ref: ref('public_users', 'id')
aggregation: 'sum'
}
}
}
}
*/

Function scope

  • Declaring a function creates a new scope. Variables and parameters declared inside a function are not accessible from outside it. However, a function can access all variables and functions defined in the scope where it was created.

    Func sum_then_double(a: Number, b: Number) => Number {
    const factor = 2;

    (a + b) * factor
    }

    a // cannot refer to a here, as it is outside of the function scope
    b // ^ same
    c // ^ same

  • Currently, AML allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to)

  • However, the outer function does not have access to the variables and functions defined inside the inner function

    Func sum_then_double(a: Number, b: Number) => Number {
    Func sum(a: Number, b: Number) {
    a + b // a, b is parameters of inner function sum
    }

    const factor = 2;

    sum(a, b) * factor // a, b is parameters of sum_then_double
    }

    sum_then_double(2, 3) // 10

Use cases


Let us know what you think about this document :)