Skip to content

Functions

AxelHumeau edited this page Jan 14, 2024 · 2 revisions

How to define a function

The "fn" keyword

The most common way to define a function would be the fn keyword. When using fn, you will define a function this way:

fn [name of the function](| [parameters of the function] |) {|
   ...
|}

fn [name of the function](| [parameters of the function] |) {| ... |} # you can also write in one line

Parameters of a function must be separated with ,.

Examples

fn foo(|a|) {|
    a + 1
|}

fn bar(|a, b|) {|
   a * b
|}

The "lambda" keyword

Another way to make function is with the lambda (or λ) keyword.

The syntax is written this way:

lambda (| [parameters of the function] |) {|
    ...
|}

λ (| [parameters of the function] |) {|
    ...
|}


λ (| [parameters of the function] |) {| ... |} # you can also write in one line

When using the lambda keyword, you have to define a variable with the lambda to use it as a function later on.

Examples

square = λ (| x |) {| x * x |}

add = λ (| a, b |) {| a + b |}

square(| 5 |) # return 25

add(| 2, 9 |) # return 11

abs = λ (| x |) {|
    if x < 0 {|
        x * -1
    |} else {|
        x
    |}
|}

abs(| -543 |) # return 543

Content of a function

A function's content is always one expression, if you need to do multiple expression in the same function, for example set a variable than use it in an addition, you have to use the $ (then) operator, which evaluate the expression at the left then the one at the right.

fn foo(| a |) {|
    b = a * 5
    if b % 4 > 0 {|
        a
    |} else {|
        b
    |}
|}
# invalid because there is the define expression `b = a * 5` and the if expression `if b % 4 > 0 {| a |} else {| b |}`

fn foo(| a |) {|
    b = a * 5 $
    if b % 4 > 0 {|
        a
    |} else {|
        b
    |}
|}
# with the $ operator, the function have now only one expression

Currying

In LobsterLang, the functions are curried, that means passing one parameter to a function that takes normally 3 is valid. When passing less parameter, the call to the functions return a new function taking less parameters.

fn foo(|a, b|) {|
   a * b
|}

bar = foo(| 5 |) # returns a new function taking only b as parameter

bar(| 8 |) # equivalent to foo(| 5, 8 |)
bar(| 9 |) # equivalent to foo(| 5, 9 |)

This can be useful in case of passing a function parameter.

release

Documentation

Tests

Clone this wiki locally