Functional Programming
THT has some essential features that support functional-style programming.
This lets you create higher-order functions, which are functions that take another function as an argument.
Anonymous Functions
An anonymous function (anon function) is a nameless function that can be assigned to a variable.
$fnIsBigNumber = fun ($num) { return $num >= 9000 }
You can directly call a function that is assigned to a variable.
$fnIsBigNumber(1) //= false $fnIsBigNumber(10_000) //= true
Because it is a variable, it can then be passed as an argument into other functions. Functions taking functions!
checkPowerLevel($fnIsBigNumber) // ... fun checkPowerLevel($fnCheck) { $powerLevel = getPowerLevel() if $fnCheck($powerLevel) { print('You are powerful enough.') } else { print('You need to level up.') } }
Closures
Anon functions are like like any other block (e.g. if
) in that they have access to the variables that exist in the outer scope.
However, since an anon function can be passed as an argument to other parts of your code (i.e. to a different scope), it holds onto the outer variables in whatever state they were in at the moment the function was declared (not when it is called).
This binding of an anon function to its outer variables is called a closure.
// Return a function that logs events from // different sources. fun newLogger($source) { $fnLogEvent = fun ($message) { File.log($source ~ ': ' ~ $message) // ^^^^^^^ from outer scope } return $fnLogEvent } $fnLogUserEvent = newLogger('user-123') $fnLogSystemEvent = newLogger('SYSTEM') $fnLogUserEvent('Login from ' ~ Request.getIp()) //= 'user-123: Login from 123.45.67.543' $fnLogSystemEvent('[shut down]') //= 'SYSTEM: [shut down]'
Expression Functions
Use the x{...}
shortcut to create an anon function that automatically returns the result of a single expression.
Expression functions automatically define arguments $a
, $b
, and $c
for the 1st, 2nd, and 3rd arguments, respectively.
x{ $a * 10 } // is the same as... fun ($a) { return $a * 10 }
Examples:
// sort players by score $topPlayers.sort(x{ $a.score <=> $b.score }) // reverse each word 'abc 123'.replace(rx'\w+', x{ $a.reverse() }) //= 'cba 321'
List Methods
The List type provides some essential functional programming methods. These apply the given function to each item in the list.
$numbers = [1, 2, 3, 4, 5] $numbers.map(x{ $a * 10}) //= [10, 20, 30, 40, 50] $numbers.reduce(x{ $a + $b }) //= 15 $numbers.filter(x{ $a % 2 == 1 }) //= [1, 3, 5] $numbers.all(x{ $a < 10 }) //= true $numbers.any(x{ $a > 100 }) //= false