Declaring Functions
Functions
A function is a construct that accepts input and returns output, executing the expressions or statements within it.
New functions are declared using the function
keyword.
At least 1 parameter must be declared, and each parameter must have a data type declared after its name. The return type must also be included in the function declaration.
The last expression of a function is implicitly returned.
Syntax
function NAME( PARAMETERS ) -> RETURN TYPE { BODY; }
Example
Declare a function
named square
which returns x * x
:
flex
function square(x : float64) -> float64 {x * x;}
Variables
Variables may be declared within the scope of a function using the let
keyword.
Syntax
let NAME = EXPRESSION;
Example
Declare a variable named sq
that is equal to x * x
:
flex
function squarePlusOne(x : float64) -> float64 {let sq = x * x;sq + 1.0;}
The last expression sq + 1.0
is returned.
Conditional Statements
Conditional statements may be included using the if
, else if
, and else
keywords.
Syntax
if ( TEST EXPRESSION ) { THEN STATEMENTS; } else { ELSE STATEMENTS; }
Example
Declare a function
named AntiqueOrVintage
which returns a string
conditionally based upon an age
parameter:
flex
function AntiqueOrVintage(age : uint8) -> string {if (age >= 100) {"Antique";} else if (age >= 40) {"Vintage";} else {"Neither";};}
The braces can be omitted for singe line statements:
flex
function AntiqueOrVintage(age : uint8) -> string {if (age >= 100) "Antique" else if (age >= 40) "Vintage" else "Neither";}
Built-in Functions
length
length(x)
Return the length of x
where x
is an array.
flex
function length(x : Array) -> int32
floor
floor(x)
Return the floor of x
where x
is a float64.
flex
function floor(x : float64) -> float64
float64to32
float64to32(x)
Return the 32 bit version of x
where x
is a float64.
flex
function float64to32(x : float64) -> float32
sin
sin(x)
Return the sine of x
where x
is a float64 in radians.
flex
function sin(x : float64) -> float64
cos
cos(x)
Return the cosine where x
is a float64 in radians.
flex
function cos(x : float64) -> float64
tan
tan(x)
Return the tangent where x
is a float64 in radians.
flex
function tan(x : float64) -> float64
sqrt
sqrt(x)
Return the square root of x
where x
is a float64.
flex
function sqrt(x : float64) -> float64
pow
pow(x,y)
Return x
raised to the power of y
where x
and y
are both float64.
flex
function pow(x : float64, y : float64) -> float64
some
some(x)
Constructor for an option that has a value x
. Used with optional data types, and pattern matching. For more details see Pattern Matching > Some and None
getOrElse
getOrElse(x,y)
Return x
if it is present, or a default value y
when it's not present. Used with optional data types, and value casting. For more details see Value Casting.