Loading...
 
Print

Examples


Here are some examples in lang5 with explanations:


: throw_dice # Define new word
    # Make a vector [6 6 6 ... 6]
    6 over reshape

    # Throw dice 100 times,
    # retain integer part and
    # make sure result is
    # between 1 and 6:
    ? int 1 +

    # Sum over all results and
    # divide by the number of
    # values:
    '+ reduce swap /
;

100 throw_dice .
The lang5 program shown on the left simulates a dice which is thrown 100 times. The results are then used to calculate the arithmetic mean.
Using the array language features of lang5 this task can be readily solved without using a loop construction. The main idea is to create a vector containing 100 elements with a value of 6 each. This is done by applying the reshape function to the scalar 6 and the number of runs which should be performed. This yields a vector 6 6 6 .. 6.
This vector is then used as argument for the dice operator ? which pulls this vector from the TOS and pushes a result vector containing 100 pseudo random values between 0 and 6 (exclusively).
In the following the int operator is applied to this vector returning a vector with integer elements between 0 and 5. Adding 1 shifts these elements one up.
To add all vector elements together, the operator + is pushed onto the stack and then the reduce operator is called. This operator applies an operator found at the TOS to the elements of a vector found below the TOS element in a way that this operator is written between all elements of this vector. The result is a scalar representing the sum of all vector elements which is then divided by the number of elements found in the vector yielding the desired arithmetic mean.