\chapter{Conditionals and recursion}
\label{conditionals}

The main topic of this chapter is the {\tt if} statement, which
executes different code depending on the state of the program.
But first we want to introduce two new operators: integer
division and modulo.

\section{Integer division and modulo}

The {\bf integer division} operator, \verb"div", divides
two numbers and rounds down to an integer.  For example,
suppose the
run time of a movie is 105 minutes.  You might want to know how
long that is in hours.  In Perl, conventional division
returns a rational number (in many languages, it returns a
floating-point number, which is another kind of internal
representation for non-integer numbers):

\begin{verbatim}
> my $minutes = 105;
> $minutes / 60;
1.75
\end{verbatim}

But we don't normally write hours with decimal points.  Integer
division returns the integer number of hours, dropping the
fraction part:
\index{operator!div}
\index{div operator}
\index{integer division}

\begin{verbatim}
> my $minutes = 105;
> my $hours = $minutes div 60;
1
\end{verbatim}

In arithmetic, the integer division is sometimes called
\emph{Euclidean division}, which computes a quotient and a
remainder.
\index{Euclidean division}
\index{division remainder}

To get the remainder, you could subtract off one hour in minutes:

\begin{verbatim}
> my $remainder = $minutes - $hours * 60;
45
\end{verbatim}

\index{integer division}
\index{floating-point division}
\index{division!integer}
\index{division!floating-point}
\index{modulo operator}
\index{operator!modulo}

An alternative is to use the {\bf modulo operator}, \verb"%", which
divides two numbers and returns the remainder.
%\index{$%$ modulo operator}
%\index{operator!$%$ (modulo)}

\begin{verbatim}
> my $remainder = minutes % 60;
45
\end{verbatim}
%
The modulo operator is very common in programming languages
and is more useful than it seems.  For example, you can
check whether one number is divisible by another---if
{\tt \$dividend \% \$divisor} is zero, then {\tt \$dividend}
is divisible by {\tt \$divisor}. This is commonly use, for
example, with a divisor equal to 2 in order to determine
whether an integer is even or odd. We will see an example
of that later in this chapter (see Section~{alternative.execution}).
\index{divisibility}
\index{even number}
\index{odd number}
\index{integer!even}
\index{integer!odd}

To tell the truth, Perl~6 also has a specific operator for
divisibility, \verb"%%". The \verb'$dividend %% $divisor'
expression returns a true value if
\verb'$divisor % $dividend' is equal to 0,
that is if {\tt \$dividend} is divisible by {\tt \$divisor} (and false otherwise):
\index{divisibility!operator}

Also, you can extract the right-most digit
or digits from a number with the modulo operator.  For example, {\tt \$x \% 10} yields the
right-most digit of {\tt \$x} (in base 10).  Similarly, {\tt \$x \% 100}
yields the last two digits:

\begin{verbatim}
> 642 % 100;
42
\end{verbatim}
%
\index{modulo operator}
\index{operator!modulo}

\section{Boolean expressions}
\index{Boolean expression}
\index{expression!Boolean}
\index{logical operator}
\index{operator!logical}

A {\bf Boolean expression} is an expression that is either true
or false.  The following examples use the operator {\tt ==},
which compares two numeric operands and produces
{\tt True} if they are equal and {\tt False} otherwise:

\begin{verbatim}
> 5 == 5;
True
> 5 == 6;
False
\end{verbatim}
%
{\tt True} and {\tt False} are special
values that belong to the type {\tt Bool}; they are not strings:
\index{True!special value}
\index{False!special value}
\index{special value!True}
\index{special value!False}
\index{Bool type}
\index{type!Bool}

\begin{verbatim}
> say True.WHAT
(Bool)
> say False.WHAT
(Bool)
\end{verbatim}
%
\index{operator!$==$ (numeric equality)}
\index{$==$ numeric equality operator}
The {\tt ==} operator is one of the {\bf numeric relational operators}
and checks whether the operands are equal; the others are:

\begin{verbatim}
      $x != $y            # $x is not numerically equal to $y
      $x > $y             # $x is  numerically greater than $y
      $x < $y             # $x is  numerically less than $y
      $x >= $y            # $x is  numerically greater than or equal to $y
      $x <= $y            # $x is  numerically less than or equal to $y
      $x === $y           # $x and $y are truly identical
\end{verbatim}
% TODO: get these entries working in plastex
\ifplastex \else
\index{"!= numeric inequality operator@\texttt{"!=} numeric inequality operator}
\index{< less than numeric operator@\texttt{<} less than numeric operator}
\index{> greater than numeric operator@\texttt{>} greater than numeric operator}
\index{>= greater than or equal operator@\texttt{>=} greater than or equal operator}
\index{<= less than or equal operator@\texttt{<=} less than or equal operator}
\index{=== value identity operator@\texttt{===} value identity operator}
\index{operator!"!= (numeric inequality)@\texttt{"!=} (numeric inequality)}
\index{operator!< (numerically less than)@\texttt{<} (numerically less than)}
\index{operator!> (numerically greater than)@\texttt{>} (numerically greater than)}
\index{operator!>= (greater than or equal)@\texttt{>=} (greater than or equal)}
\index{operator!<= (less than or equal)@\texttt{<=} (less than or equal)}
\index{operator!=== (value identity)@\texttt{===} (value identity)}
\fi
Although these operations are probably familiar to you, the Perl
symbols are different from the mathematical symbols.  A common error
is to use a single equal sign ({\tt =}) instead of a double equal sign
({\tt ==}).  Remember that {\tt =} is an assignment operator and
{\tt ==} is a relational operator.   There is no such thing as
{\tt =<}, and there exists a {\tt =>} operator, but it is not a relational
operator, but something completely different (it is,  as we'll see later, a pair constructor).
\index{relational operator}
\index{relational operator!numeric}
\index{numeric relational operator}
\index{equality operator}
\index{operator!equal}
\index{operator!relational}
\index{pair constructor}
\index{constructor!pair}
% TODO: get these entries working in plastex
\ifplastex \else
\index{=> pair constructor@\texttt{=>} pair constructor}
\index{operator!=> (pair constructor)@\texttt{=>} (pair constructor)}
\fi

The difference between {\tt ==} and {\tt ===} is that the
former operator checks whether the values of the operands
are equal and the latter checks whether the operands are
truly identical. As an example, consider this:

\begin{verbatim}
say 42 ==  42;           # True
say 42 ==  42.0;         # True
say 42 ===  42;          # True
say 42 === 42.0;         # False
\end{verbatim}
%

These relational operators can only compare numeric values
(numbers or variables containing numbers) or values that
can be coerced to numeric values, such as, for example,
the string "42" which, if used with these operators
(except {\tt ===}), will be coerced to number 42.
\index{coercion}

For comparing strings (in a lexicographic or ``pseudo
alphabetic'' type of comparison), you need to use
the {\bf string relational operators}:

\begin{verbatim}
      $x eq $y            # $x is string-wise equal to $y
      $x ne $y            # $x is string-wise not equal to $y
      $x gt $y            # $x is greater than $y (alphabetically after)
      $x lt $y            # $x is less than $y (alphabetically before)
      $x ge $y            # $x is greater than or equal to $y
      $x le $y            # $x is less than or equal to $y
      $x eqv $y           # $x is truly equivalent to $y
\end{verbatim}
%
\index{relational operator}
\index{relational operator!string}
\index{string!relational operator}
\index{operator!relational}
\index{eq, string equality operator}
\index{operator!eq (string equality)}
\index{ne, string inequality operator}
\index{operator!ne (string inequality)}
\index{operator!gt (alphabetically after)}
\index{operator!lt (alphabetically before)}

For example, you may compare (alphabetically) two former
US presidents:
\begin{verbatim}
> 'FDR' eq 'JFK';
False
> 'FDR' lt 'JFK';    # alphabetical comparison
True
\end{verbatim}
%

Unlike most other programming languages, Perl~6 allows you to chain relational operators transitively, just as in mathematical notation:

\begin{verbatim}
say 4 < 7 < 12;      # True
say 4 < 7 < 5;       # False
\end{verbatim}
\index{chained relational operator}

It may be useful to point out that numeric relational operators
and string relational operators don't work the same way (and
that's a good reason for having different operators), because
they don't have the same idea of what is \emph{greater than}
or \emph{less than}.

When comparing two positive integers, a number with four digits
is always greater than a number with only two or three digits.
For example, 1110 is greater than 886.

String comparisons, in contrast, basically follow (pseudo) alphabetical rules: 'b' is greater than 'aaa', because the commonly accepted rule for string comparisons is to start by comparing the first letter of each string: which string is greater is known if the two letters are different, irrespective of what character comes next; you need to proceed to comparing the second letter of each word only if comparing the first letter of each string led to a draw, and so on. Thus, any word starting with 'a' is less than any word starting with 'b', irrespective of the length of these words. You may think that this is nitpicking, but this becomes essential when you start sorting items: you really have to think about which type of order (numeric or alphabetical) you want to use.
\index{sorting}

There are also some so-called ``three-way'' relational operators,
{\tt cmp}, {\tt <=>} and {\tt leg}, but we'll come back to them
when we study how to sort the items of a list. Similarly, we need
to learn quite a few other things about Perl before we can do
justice to the incredibly powerful and expressive smart match
operator, \verb"~~".
\index{sorting}
\index{smart match operator}
\index{operator!smart match}
\index{three-way operator}
\index{operator!three-way}
\index{cmp operator}
\index{leg operator}
\index{operator!leg}
% TODO: get these entries working in plastex
\ifplastex \else
\index{<=> operator@\texttt{<=>} operator}
\index{operator!<=> (numeric comparison)@\texttt{<=>} (numeric comparison)}
\fi

A final point to be noted about string comparisons is
that uppercase letters are always deemed smaller
than lowercase letters. So "A", "B", "BB" and "C"
are \emph{all} less than "a", "b", "bb" and "c". We
will not go into the details here, but this becomes
more complicated (and sometimes confusing) when
the strings to be compared contain non alphabetical
characters (or non ASCII Unicode letters).

\section{Logical operators}
\index{logical operator}
\index{operator!logical}

There are three main pairs of {\bf logical operators}:
\begin{itemize}
\item logical \emph{and}: ``{\tt and}'' and {\tt \&\&},
\item logical \emph{or}: ``{\tt or}'' and {\tt ||},
\item logical \emph{not}: ``{\tt not}'' and {\tt !}.
\end{itemize}

The semantics (meaning) of these operators is
similar to their meaning in English.  For example,
{\tt \$x > 0 and \$x < 10} is true only if {\tt \$x} is greater
than 0 {\em and} less than 10.
\index{and operator}
\index{or operator}
\index{not operator}
\index{operator!and}
\index{operator!or}
\index{operator!not}

{\tt \$n \% 2 == 0 and \$n \% 3 == 0} is true if {\em both}
conditions are true, that is, if the number is divisible by 2
{\em and} by 3, i.e. is in fact divisible by 6 (which could be better
written as: {\tt \$n \% 6 == 0} or {\tt \$n \%\% 6}).

{\tt \$n \% 2 == 0 or \$n \% 3 == 0} is true if {\em either or
both} of the conditions is true, that is, if the number is
divisible by 2 {\em or} by 3 (or both).

Finally, the {\tt not} operator negates a boolean
expression, so {\tt not (x > y)} is true if {\tt x > y}
is false, that is, if {\tt x} is less than or equal
to {\tt y}.

The {\tt \&\&}, {\tt ||} and {\tt !} operators have the same
meanings, respectively, as {\tt and}, {\tt or} and {\tt not},
but they have a tighter precedence, which means that when
they stand in an expression with some other operators,
they have a higher priority of execution. We will come
back to precedence later, but let's say for the time being
that, in most common cases, the {\tt and}, {\tt or} and
{\tt not} operators will usually do what you want.
\index{precedence}
\index{operator precedence}

Strictly speaking, the operands of the logical operators should
be boolean expressions, but Perl, just like many languages
partly derived from C, is not very strict on that. The
numbers~0 and 0.0 are false; and any nonzero number
or nonempty string is interpreted as {\tt True}:

\begin{verbatim}
> 42 and True;
True
\end{verbatim}
%
This flexibility can be very useful, but there are some
subtleties to it that might be confusing.  You might want
to avoid it unless you know what you are doing.

The {\tt so} built-in function returns a boolean evaluation of
its argument:

\begin{verbatim}
> say so (0 and True);
False
\end{verbatim}
%
Here, the expression {\tt (0 and True)} is false because 0
is false and the expression could be true only if both arguments
of the {\tt and} operator were true.

When several boolean conditions are linked with some logical
operator, Perl will only perform the comparisons that are
strictly necessary to figure out the final result, starting
with those on the left. For example, if you write:

\begin{verbatim}
> False and $number > 0;
False
\end{verbatim}
%
there is no need to evaluate the second boolean expression
to know that the overall expression will be false. In this case,
Perl does not try to check whether the number is positive or
even whether it is defined. It is sometimes said that
these operators ``short circuit'' unnecessary conditions.
\index{short-circuit boolean operators}
\index{short-circuit evaluation}

Similarly, in the following code, the {\tt compute-pension}
subroutine will not even be called if the person's age is
less than 65:

\begin{verbatim}
$age >= 65 and compute-pension();
\end{verbatim}
%
The same goes with the {\tt or} operator, but in the other way
around: if the first boolean expression of an {\tt or}
statement is true, then the next expression will not be
evaluated. The following code is thus equivalent to the previous
one:

\begin{verbatim}
$age < 65 or compute-pension();
\end{verbatim}
%
This \emph{can} be a way of running the {\tt compute-pension}
subroutine conditionally, depending on the value of the age, and
this is sometimes used, notably in idiomatic constructs such as:
\index{idiomatic}

\begin{verbatim}
do-something() or die "could not do something";
\end{verbatim}
%
which aborts the program if {\tt do-something} returns a false
value, meaning that it was not able to do something
so essential that it would not make sense to try to continue
running it.

We will examine now clearer and much more common
ways of running conditional code.

\section{Conditional execution}
\label{conditional.execution}

\index{conditional!statement}
\index{statement!conditional}
\index{if statement}
\index{statement!if}
\index{conditional!execution}
In order to write useful programs, we almost always need the ability
to check conditions and change the behavior of the program
accordingly.  {\bf Conditional statements} give us this ability.  The
simplest form is the {\tt if} statement:

\begin{verbatim}
if $number > 0 {
    say '$number is positive';
}
\end{verbatim}
%
The boolean expression after {\tt if} is called the
{\bf condition}.  If it is true, the subsequent
block of code runs.  If not, nothing happens. The block of
code may contain any number of statements.
\index{condition}

It is conventional and highly recommended (although not
strictly mandatory from the standpoint of the compiler)
to indent the statements in the block, in order to help
visualize the \emph{control flow} of the program, i.e.
its structure of execution: with such indentation, we
can see much better that the statements within the
conditional block will run only if the condition is true.
\index{indentation}

The condition may be a compound boolean expression:
\begin{verbatim}
if $n > 0 and $n < 20 and $n %% 2 {
    say '$n is an even and positive number smaller than 20'
}
\end{verbatim}
%
Note that in the print statement above, the final semi-colon
has been omitted. When a statement is the last code line of
a block, immediately before the curly brace {\tt \}} closing
that code block, the final semi-colon is optional and may
be omitted, though it might be considered good form to include it.
\index{omitting the semi-colon}
\index{semi-colon, omitting}
\index{bracket!curly}
\index{curly bracket}
\index{curly brace}

In theory, the overall code snippet above is itself a statement
and should also end with a semi-colon after the closing brace.
But a closing curly brace followed by a newline character implies a statement separator, so you don't need a semi-colon here and it is generally omitted.
\index{omitting the semi-colon}
\index{semi-colon, omitting}

\section{Alternative execution}
\label{alternative.execution}
\index{alternative execution}
\index{else keyword}
\index{keyword!else}

A second form of the {\tt if} statement is ``alternative execution'',
in which there are two possibilities and the condition determines
which one runs.  Given a \verb'$number' variable containing an
integer, the following code displays two different messages
depending on whether the value of the integer is even or odd::

\begin{verbatim}
if $number % 2 == 0 {
    say 'Variable $number is even'
} else {
    say 'Variable $number is odd'
}
\end{verbatim}
%
\index{even number}
\index{odd number}
\index{integer!odd}
\index{integer!even}
If the remainder when {\tt \$number} is divided by 2 is 0,
then we know that {\tt \$number} is even, and the program
displays an appropriate message.  If
the condition is false, the second set of statements runs.
Since the condition must be true or false, exactly one of the
alternatives will run.  The alternatives are called
{\bf branches}, because they are branches in the flow of
execution.
\index{branch}

Note that if \verb'$number' is evenly divisible by two,
this code will print:

\begin{verbatim}
Variable $number is even
\end{verbatim}

literally, without interpolating the \verb'$number' variable
value, because we have used single quotes for the purpose
of printing out the variable name rather
than its value. We would have to use double quotes if
we wanted to display the variable's value instead of its
name.
\index{single quote}
\index{double quote}
\index{quote!single}
\index{quote!double}
\index{variable!interpolation}
\index{interpolation}

\section{Chained conditionals}
\index{chained conditional}
\index{conditional!chained}

Sometimes there are more than two possibilities and we need more than
two branches.  One way to express a computation like that is a
{\bf chained conditional}:

\begin{verbatim}
if $x < $y {
    say 'Variable $x is less than variable $y'
} elsif $x > $y {
    say 'Variable $x is greater than variable  $y'
} else {
    say 'Variables $x and $y are equal')
}
\end{verbatim}
%
The {\tt elsif} keyword is an abbreviation of ``else if'' that
has the advantage of avoiding nesting of blocks. Again, exactly one
branch will run.  There is no limit on the number of {\tt
elsif} statements.

If there is an {\tt else} clause, it has to be
at the end, but there doesn't have to be one.
\index{elsif keyword}
\index{keyword!elsif}

\begin{verbatim}
if $choice eq 'a' {
    draw_a()
} elsif $choice eq 'b' {
    draw_b()
} elsif $choice eq 'c' {
    draw_c()
}
\end{verbatim}
%
Each condition is checked in order.  If the first is false,
the next is checked, and so on.  If one of them is
true, the corresponding branch runs and the statement
ends.  Even if more than one condition is true, only the
first true branch runs.

\section{Nested conditionals}
\index{nested conditional}
\index{conditional!nested}

One conditional can also be nested within another.  We could have
written the example in the previous section like this:

\begin{verbatim}
if $x == $y {
    say 'Variables $x and $y are equal'
} else {
    if $x < $y {
        say 'Variable $x is less than variable $y'
    } else {
        say 'Variable $x is greater than variable $y'
    }
}
\end{verbatim}
%
The outer conditional contains two branches.  The
first branch contains a simple statement.  The second branch
contains another {\tt if} statement, which has two branches of its
own.  Those two branches are both simple statements,
although they could have been conditional statements as well.
The \verb'if $x < $y' conditional is said to be nested within
the {\tt else} branch of the outer conditional.

Such nested conditionals show how critical it is for your
own comprehension to properly indent conditional statements,
as it would be very difficult here to visually grasp the
structure without the help of correct indentation.
\index{indentation}

Although the indentation of
the statements helps make the structure apparent,
{\bf nested conditionals} become difficult to read very
quickly.  It is a good idea to avoid them when you can.
Logical operators often provide a way to simplify nested
conditional statements.  For example, consider the
following code (which assumes \verb'$x' to be an integer):
\index{logical operator}

\begin{verbatim}
my Int $x;
# ... $x = ...;
if 0 < $x {
    if $x < 10 {
        say 'Value of $x is a positive single-digit number.'
    }
}
\end{verbatim}
%
The {\tt say} statement runs only if we make it past both
conditionals, so we can get the same effect with the {\tt and}
boolean operator, and the code can be rewritten using a
single conditional:

\begin{verbatim}
if 0 < $x and $x < 10 {
    say '$x is a positive single-digit number.'
}
\end{verbatim}

For this kind of conditions, Perl~6 provides a more concise
option using the chained relational operators described earlier:

\begin{verbatim}
if 0 < $x < 10 {
    say '$x is a positive single-digit number.'
}
\end{verbatim}
\index{chained relational operator}

\section{If conditionals as statement modifiers}
\index{statement modifier} \index{modifier!statement}
\index{postfix conditional} \index{conditional!postfix }

There is also a form of {\tt if} called a {\bf statement
modifier} (or sometimes  ``postfix conditional'') form when there is only
one conditional statement. In this case, the {\tt if} and the
condition come after the code you want to run conditionally. Note
that the condition is still always evaluated first:

\begin{verbatim}
say '$number is negative.' if $number < 0;
\end{verbatim}
%
is equivalent to:
\begin{verbatim}
if $number < 0 {
    say '$number is negative.'
}
\end{verbatim}
%
This syntactic form is more concise as it takes only one code
line instead of three. The advantage is that you can see more
of your program code on one screen, without having to scroll up
and down. However, this syntax is neat and clean only when
both the condition and the statement are short and simple, so it
is probably best used only in these cases.

The statement modifier form does not allow {\tt else} and
{\tt elsif} statements.

\section{Unless conditional statement}
\index{unless statement}
\index{keyword!unless}

If you don't like having to write negative conditions in a conditional
{\tt if} statement such as:
%
\begin{verbatim}
if not $number >= 0 {
    say '$number is negative.'
}
\end{verbatim}
%

you may write instead this:
\begin{verbatim}
unless $number >= 0 {
    say '$number is negative.'
}
\end{verbatim}
%
This {\bf unless} keyword does exactly what the English says:
it will display the sentence ``\$number is negative.''
\emph{unless} the number is greater than or equal to 0.

You cannot use {\tt else} or {\tt elsif} statements with
{\tt unless}, because that would end up getting confusing.

The {\tt unless} conditional is most commonly used in its statement modifier (or postfix notation) form:

\index{statement modifier} \index{modifier!statement}
\index{postfix conditional} \index{conditional!postfix }

\begin{verbatim}
say '$number is negative.' unless $number >= 0;
\end{verbatim}
%

\section{For loops}
\label{for_loops}
\index{for loop}
\index{loop!for}
\index{statement!for}
\index{factorial}

Suppose you need to compute and print the product of the first
five positive digits (1 to 5). This product is known in mathematics
as the \emph{factorial} of 5 and sometimes written as $5!$. You could write this program:

\begin{verbatim}
my $product = 1 * 2 * 3 * 4 * 5;
say $product;           # prints 120
\end{verbatim}
%

You could make it slightly simpler:
\begin{verbatim}
say 2 * 3 * 4 * 5;      # prints 120
\end{verbatim}
%

The problem is that this syntactic construct does
not scale well and becomes tedious for the product of the first
ten integers (or factorial 10). And it becomes almost a
nightmare for factorial 100.
Calculating the factorial of a number is a fairly common computation
in mathematics (especially in the fields of combinatorics
and probability) and in computer science. We need to
automatize it, and using a {\tt for}
loop is one of the most obvious ways of doing that.
\index{factorial!using a for loop}

\begin{verbatim}
my $product = 1;
for 1..5 {
    $product *= $_
}
say $product;           # prints 120
\end{verbatim}

Now, if you need to compute factorial 100, you just need to
replace the 5 in the code above with 100. Beware, though,
the factorial function is known to grow extremely rapidly,
and you'll get a truly huge number, with 158 digits
(i.e. a number much larger than the estimated total
number of atoms in the known universe).
\index{factorial}

\index{range!operator}
\index{operator!range}
\index{special variable}
In this script, {\tt 1..5} is the range operator, which is used here
to generate a list of consecutive numbers between 1 and 5. The
{\tt for} keyword is used to iterate over that list, and
\verb"$_" is a special variable which takes each successive
value of this list: first 1, then 2, etc. until 5. In the code
block forming the body of the loop, the {\tt \$product} variable
is multiplied successively by each value of \verb"$_". The loop
ends with 5 and the result, 120, is printed in the last line.

This is a simple use of the {\tt for} statement,
but probably not the most commonly used in Perl~6;
we will see more below. We will also see other types of loops.
But that should be enough for now to let you write some loops. Loops
are found everywhere in computer programming.

\index{special variable}
\index{topical variable}
\index{default method invocant}
\index{invocant}
\index{topic}
The \verb"$_" special variable is known as the \emph{topical
variable} or simply the \emph{topic}. It does not need to be declared
and many syntactic constructs assign a value to it without
explicitly mentioning it. Also, \verb"$_" is a implicit argument
to methods called without an explicit invocant. For example,
to print the first five integers, you might write:

\begin{verbatim}
for 1..5 {.say};  # prints numbers 1 to 5, each on its line
\end{verbatim}

Here {\tt .say} is a syntax short hand equivalent to \verb"$_.say".
And since, as we saw, \verb"$_" takes each successive value of
the range introduced by the {\tt for} keyword, this very short code
line prints each number between 1 and 5, each on a different line.
This is a typical example of the \verb"$_" topical variable being used
without even being explicitly mentioned. We will see many other
uses of the \verb"$_" special variable.

Sometimes, you don't use the \verb"$_" loop variable within the
loop, for example if you just want to do something 5 times but don't
care each time through the loop at which iteration you
have arrived. A subroutine that prints a message \emph{n} times
might look like this:

\begin{verbatim}
sub print-n-times (Int $n, Str $message) {
    for 1..$n { say $message }
}
\end{verbatim}

The {\tt for} loop also has a statement modifier or postfix form
used here to compute again the factorial of 5:
\index{statement modifier}
\index{postfix notation}
\index{factorial!using a for statement modifier}

\begin{verbatim}
my $product = 1;
$product *= $_ for 1..5;
say $product;           # prints 120
\end{verbatim}

There is another syntax for the {\tt for} loop, using an explicit loop variable:
\index{factorial!using a for pointy block }

\begin{verbatim}
sub factorial (Int $num) {
    my $product = 1;
    for 1..$num -> $x {
        $product *= $x
    }
    return $product
}
say factorial 10;   # 3628800
\end{verbatim}

The {\tt for} loop in this subroutine is using what is called
a ``pointy block'' syntax. It is essentially the same idea
as the previous {\tt for} loops, except that,
instead of using the \verb"$_" topical variable, we
now declare an explicit \verb"$x" loop variable with the
\verb"1..$num -> $x" syntax to iterate over the range
of values. Using an explicit loop variable can make your
code clearer when things get more complicated, for example
when you need to nest several {\tt for} loops. We will
see more examples of that later.
\index{pointy block}
\index{for loop}
\index{loop!for}

We will also see several other ways of computing the factorial
of a number in this book.
\index{factorial}

\section{Recursion}
\label{recursion}
\index{recursion}

It is legal for one function or subroutine to call another;
it is also legal for a subroutine to call itself.  It may not
be obvious why that is a good thing, but it turns out to be
one of the most magical things a program can do.
For example, look at the following subroutine:

\begin{verbatim}
sub countdown(Int $time-left) {
    if $time-left <= 0 {
        say 'Blastoff!';
    } else {
        say $time-left;
        countdown($time-left - 1);
    }
}
\end{verbatim}
%
If {\tt \$n} is 0 or negative, it outputs the word,
``Blastoff!''. Otherwise, it outputs {\tt \$time-left}
and then calls a subroutine named {\tt countdown}---itself---
passing {\tt \$n-1} as an argument.

What happens if we call this subroutine like this?

\begin{verbatim}
countdown(3);
\end{verbatim}
%
The execution of {\tt countdown} begins with {\tt \$time-left
= 3}, and since {\tt \$time-left} is greater than 0, it
outputs the value 3, and then calls itself...

\begin{quote}
The execution of {\tt countdown} begins with {\tt \$time-left = 2}, and since
{\tt \$time-left} is greater than 0, it outputs the value 2, and then calls itself...

\begin{quote}
The execution of {\tt countdown} begins with {\tt \$time-left = 1}, and since
{\tt \$time-left} is greater than 0, it outputs the value 1, and then calls itself...

\begin{quote}
The execution of {\tt countdown} begins with {\tt \$time-left = 0}, and since {\tt
\$time-left} is not greater than 0, it outputs the word, ``Blastoff!'' and then
returns.
\end{quote}

The {\tt countdown} that got {\tt \$time-left = 1} returns.
\end{quote}

The {\tt countdown} that got {\tt \$time-left = 2} returns.
\end{quote}

The {\tt countdown} that got {\tt \$time-left = 3} returns.

And then you're back in the main program.  So, the
total output looks like this:

\begin{verbatim}
3
2
1
Blastoff!
\end{verbatim}
%
A subroutine that calls itself is {\bf recursive}; the process of
executing it is called {\bf recursion}.
\index{recursion}
\index{function!recursive}

As another example, we can write a subroutine that prints a
string {\tt \$n} times.

\begin{verbatim}
sub print-n-times(Str $sentence, Int $n) {
    return if $n <= 0;
    say $sentence;
    print-n-times($sentence, $n - 1);
}
\end{verbatim}
%
If {\tt \$n <= 0}, the {\bf return statement} exits the
subroutine.  The flow of execution immediately returns to
the caller, and the remaining lines of the subroutine don't
run. This illustrates a feature of the {\tt return} subroutine
that we had not seen before: it is used here for flow
control, i.e. to stop the execution of the subroutine and
pass control back to the caller. Note also that, here, the
{\tt return} statement does not return any value to the
caller; {\tt print-n-times} is a void function.

\index{return!statement}
\index{statement!return}
\index{void function}

The rest of the subroutine is similar to {\tt countdown}: it
displays {\tt \$sentence} and then calls itself to display
{\tt \$sentence} $\$n - 1$ additional times.  So the number
of lines of output is {\tt 1 + (\$n - 1)}, which
adds up to {\tt \$n}.

For simple examples like this, it may seem easier to use a {\tt
for} loop.  But we will see examples later that are hard to write
with a {\tt for} loop and easy to write with recursion, so it is
good to start early.
\index{for loop}
\index{loop!for}

\section{Stack diagrams for recursive subroutines}
\label{recursive.stack}
\index{stack diagram}
\index{function frame}
\index{frame}

In Section~\ref{stackdiagram}, we used a stack diagram to represent
the state of a program during a subroutine call.  The same kind of
diagram can help interpret a recursive subroutine.

Every time a subroutine gets called, Perl creates a
frame to contain the subroutine's local variables and parameters.
For a recursive subroutine, there might be more than one frame
on the stack at the same time.

Figure~\ref{fig.stack2} shows a stack diagram for {\tt countdown} called with
{\tt n = 3}.

\begin{figure}
\centerline
{\includegraphics[scale=0.6]{figs/stack2.png}}
\caption{Stack diagram.}
\label{fig.stack2}
\end{figure}

As usual, the top of the stack is the frame for the main
program.
It is empty because we did not create any variables in
it or pass any arguments to it.
\index{base case}
\index{recursion!base case}

The four {\tt countdown} frames have different values for the
parameter {\tt \$time-left}.  The bottom of the stack, where {\tt \$time-left = 0}, is
called the {\bf base case}.  It does not make a recursive call, so
there are no more frames.

As an exercise, draw a stack diagram for \verb"print-n-times"
called with
\verb"$sentence = 'Hello'" and {\tt \$n = 2}.
Then write a function called \verb"do-n-times" that takes a function
and a number, {\tt \$num}, as arguments, and that calls
the given function {\tt \$num} times.
\label{do_n_times}
\emph{Solution}: see Section~\ref{sol_do_n_times}

\section{Infinite recursion}
\index{infinite recursion}
\index{recursion!infinite}
\index{runtime error}

If a recursion never reaches a base case, it goes on making
recursive calls forever, and the program never terminates.  This is
known as {\bf infinite recursion}, and it is generally not
a good idea. In fact, your program will not actually execute
forever but will die at some point when the computer runs out of
memory or some other critical resource.

You have to be careful when writing recursive subroutines.
Make sure that you have a base case, and make sure that
you are guaranteed to reach it. Actually, although this is not
absolutely required by the language, we would advise you to
take the good habit of treating the base case first.

\section{Keyboard input}
\index{keyboard input}

The programs we have written so far accept no input from
the user. They just do the same thing every time. Perl
provides built-in functions that stop the program and
wait for the user to type something.

For example, the {\tt prompt} function prompts the user with
a question or an instruction. When the user presses
{\sf Return} or {\sf Enter}, the program resumes and
\verb"prompt" returns what the user typed as a string
(without the newline character corresponding to the
{\sf Return} key typed by the user).
\index{prompt function}
\index{function!prompt}

\begin{verbatim}
my $user = prompt "Please type in your name: ";
say "Hello $user";
\end{verbatim}
%

This is probably one of the most common ways to obtain
interactive user input, because it is usually a good idea
to tell the user what is expected.

Another possibility is to use the {\tt get} method (which
 reads a single line) on standard input:
\index{get function}
\index{function!get}

\begin{verbatim}
say "Please type in your name: ";
my $user = $*IN.get;
say "Hello $user";
\end{verbatim}
%
or the {\tt get} function, which reads a line from standard input by default:
\begin{verbatim}
say "Please type in your name: ";
my $user = get;
say "Hello $user";
\end{verbatim}
%

\section{Program arguments and the MAIN subroutine}
\label{MAIN}
\index{MAIN}

There is another (and often better) way to have a program
use varying input defined by the user, which is to pass
command line arguments to the program, just as we have
passed arguments to our subroutines.

The easiest way to retrieve arguments passed to a program is
to use a special subroutine named \verb'MAIN'. A program that
has a \verb'MAIN' subroutine defined will usually start its execution
with that subroutine and the command-line arguments supplied
to the program will be passed as arguments to \verb'MAIN',
so that the \verb'MAIN' signature will enable you to
retrieve the arguments provided in the command line and
possibly also to check their validity.
\index{signature}

For example, the {\tt greet.pl6} program might look like
this:
\begin{verbatim}
sub MAIN (Str $name) {
    say "Hello $name";
}
\end{verbatim}

You may call this program twice with a changing command line
argument as follows:

\begin{verbatim}
$ perl6 greet.pl6 Larry
Hello Larry

$ perl6 greet.pl6 world
Hello world
\end{verbatim}

It is very easy to change the argument, since all you need
to do is to use the up arrow and edit the end of the
previous command line.

If you forget to supply the argument (or provide the wrong
number of arguments, or arguments not matching the signature),
the program will die and Perl~6 will nicely generate and
display a usage method:

\begin{verbatim}
$ perl6 greet.pl6
Usage:
  greet.pl6 <name>
\end{verbatim}

\section{Debugging}
\label{whitespace}
\index{debugging}
\index{traceback}

When a syntax or runtime error occurs, the error message contains
a lot of information, but it can be overwhelming.  The most
useful parts are usually:

\begin{itemize}

\item What kind of error it was, and

\item Where it occurred.

\end{itemize}

Syntax errors are usually easy to find, but there are a few
gotchas. In general, error messages indicate where the problem was discovered, but the actual error might be earlier in
the code, sometimes on a previous line or even many lines
before.
\index{multiplication tables}

For example, the following code aimed at displaying the
multiplication tables:

\begin{verbatim}
sub multiplication-tables {
    for 1..10 -> $x {
	    for 1..10 -> $y {
            say "$x x $y\t= ", $x * $y;
        say "";
	}
}

multiplication-tables();
\end{verbatim}

fails at compilation with the following error:

\begin{verbatim}
$ perl6 mult_table.pl6
===SORRY!=== Error while compiling /home/Laurent/mult_table.pl6
Missing block (taken by some undeclared routine?)
at /home/Laurent/mult_table.pl6:9
------> multiplication-tables();<HERE><EOL>
\end{verbatim}

The error message reports an error on line~9 of the program
(the last line of the code), at the end of the line, but
the actual error is a missing closing brace after line~4
and before line~5. The reason for that is that, while the
programmer made the mistake on line~4, the Perl interpreter
could not detect this error before it reached the
end of the program. The correct program for displaying
multiplication
tables might be:

\begin{verbatim}
sub multiplication-tables {
    for 1..10 -> $x {
        for 1..10 -> $y {
            say "$x x $y\t= ", $x * $y;
        }
        say "";
    }
}
multiplication-tables();
\end{verbatim}

When an error is reported on the last line of a program,
it quite commonly due to a missing closing parenthesis,
bracket, brace or quote mark several lines earlier. An editor with
syntax highlighting can sometimes help you.
\index{syntax!highlighting}

\index{error!runtime}
\index{runtime error}

The same is true of runtime errors. Consider this program aimed at computing 360 degrees divided successively by the integers between 2 and 5:

\begin{verbatim}
my ($a, $b, $c, $d) = 2, 3, 5;
my $value = 360;
$value /= $_ for $a, $b, $c, $d;
say $value;
\end{verbatim}

This programs compiles correctly but displays a warning and
then an exception on runtime:

\begin{verbatim}
Use of uninitialized value of type Any in numeric context
in block  at product.pl6 line 3
Attempt to divide 12 by zero using div
  in block <unit> at product.pl6 line 4
\end{verbatim}
%

The error message indicates a ``division by zero'' exception
on line~4, but there is nothing wrong with that line.
The warning on line~3 might give us the clue that the
script attempts to use an undefined value, but the real error
is on the first line of the script, where one of the four
necessary integers (4) was omitted by mistake from the list
assignment.

\index{division by zero}
\index{uninitialized value}

You should take the time to read error messages carefully,
but don't assume they point to the root cause of the
exception, they often point to subsequent problems.

\section{Glossary}

\begin{description}

\item[integer division:] An operation, denoted {\tt div},
that divides two numbers and rounds down (toward zero) the
result to an integer.
  \index{integer division}
  \index{division!integer}

\item[modulo operator:]  An operator, denoted with a percent sign
({\tt \%}), that works on integers and returns the remainder when one
number is divided by another.
\index{modulo operator}
\index{operator!modulo}

\item[Boolean expression:]  An expression whose value is either
{\tt True} or {\tt False}.
\index{Boolean expression}
\index{expression!Boolean}

\item[relational operator:] One of the operators that compares
its operands. The most common numeric relational operator are  {\tt ==}, {\tt !=}, {\tt >}, {\tt <}, {\tt >=}, and {\tt <=}. The equivalent string relational operator are {\tt eq}, {\tt ne}, {\tt gt}, {\tt lt}, {\tt ge}, and {\tt le}.

\item[logical operator:] One of the operators that combines boolean
expressions: {\tt and}, {\tt or}, and {\tt not}. The equivalent higher-precedence operators are {\tt \&\&}, {\tt ||}, and {\tt !}

\item[conditional statement:]  A statement that controls the
flow of execution depending on some condition.
\index{conditional!statement}
\index{statement!conditional}

\item[condition:] The boolean expression in a conditional
statement that determines which branch runs.
\index{condition}

\item[branch:] One of the alternative sequences of statements in
a conditional statement.
\index{branch}

\item[chained conditional:]  A conditional statement with a
series of alternative branches.
\index{chained conditional}
\index{conditional!chained}

\item[nested conditional:]  A conditional statement that appears
in one of the branches of another conditional statement.
\index{nested conditional}
\index{conditional!nested}

\item[statement modifier:] A postfix conditional expression, i.e.
a conditional expression (using for example {\tt if}, {\tt unless} or
{\tt for}) that is placed after the statement the executions of which
it controls. It can also refer to a postfix looping expression.
\index{statement modifier}

\item[return statement:] A statement that causes a function to
end immediately and return to the caller.

\item[recursion:]  The process of calling the function that is
currently executing.
\index{recursion}

\item[base case:]  A conditional branch in a
recursive function that does not make a recursive call.
\index{base case}

\item[infinite recursion:]  A recursion that doesn't have a
base case, or never reaches it.  Eventually, an infinite
recursion causes a runtime error, for which you may not want
to wait because it may take a long time.
\index{infinite recursion}

\end{description}

\section{Exercises}
%

\begin{exercise}
%
Using the integer division and the modulo operators:
\index{modulo operator}
\index{operator!mod}
\index{mod, modulo operator}
\index{integer division}
\index{operator!div}
\index{div operator}
\label{int_div_modulo}

\begin{enumerate}

\item Write a subroutine that computes how many days, hours, minutes and seconds there are in the number of seconds passed as an argument to the subroutine.

\item Write a script that computes how many days, hours, minutes and seconds there are in 240,000 seconds.

\item Change your script to compute the number of days, hours, minutes and seconds there are in a number of seconds entered by the script user when prompted to give a number of seconds.

\end{enumerate}

\emph{Solutions:} Subsection~\ref{sol_int_div_modulo}.

\end{exercise}

\begin{exercise}
\index{Fermat's Last Theorem}
\label{fermat_ex}

Fermat's Last Theorem says that there are no positive integers
$a$, $b$, and $c$ such that

\[ a^n + b^n = c^n \]
%
for any values of $n$ greater than 2.

\begin{enumerate}

\item Write a function named \verb"check-fermat" that takes four
parameters---{\tt a}, {\tt b}, {\tt c} and {\tt n}---and
checks to see if Fermat's theorem holds.  If
$n$ is greater than 2 and

\[a^n + b^n = c^n \]
%
the program should print, ``Holy smokes, Fermat was wrong!''
Otherwise the program should print, ``No, that doesn't work.''

\item Write a function that prompts the user to input values
for {\tt a}, {\tt b}, {\tt c} and {\tt n}, converts them to
integers, and uses \verb"check-fermat" to check whether they
violate Fermat's theorem.
\end{enumerate}

Solution: \ref{sol_fermat_ex}

\end{exercise}

\begin{exercise}
\index{triangle}
\label{triangle}

If you are given three sticks, you may or may not be able to arrange
them in a triangle.  For example, if one of the sticks is 12 inches
long and the other two are one inch long, you will
not be able to get the short sticks to meet in the middle.  For any
three lengths, there is a simple test to see if it is possible
to form a triangle:

\begin{quotation}
If any of the three lengths is greater than the sum of the other
  two, then you cannot form a triangle.  Otherwise, you
  can.  (If the sum of two lengths equals the third, they form
    what is called a ``degenerate'' triangle.)
\end{quotation}

\begin{enumerate}

\item Write a function named \verb"is-triangle" that takes three
positive numbers as arguments, and that prints either
``Yes'' or ``No'', depending on whether you can
form a triangle from sticks with the given lengths.

\item Write a function that prompts the user to input
three stick lengths and uses \verb"is-triangle" to check
whether sticks with the given lengths can form a triangle.

\end{enumerate}

Solution: \ref{sol_triangle}

\end{exercise}

\begin{exercise}
\index{Fibonacci!numbers}
\label{fibonacci}
The Fibonacci numbers were invented by Leonardo Fibonacci
(a.k.a. Leonardo of Pisa or simply Fibonacci), an Italian
mathematician of the thirteenth century.
\index{Fibonacci, Leonardo}

The Fibonacci numbers are a sequence of numbers such as:

\[1, \;1, \;2, \;3, \;5, \;8, \;13, \;21, \;34, \ldots\]
%
in which the first two numbers are equal to 1 and each
subsequent number of the sequence is defined as the sum of
the previous two (for example, $5 = 2 + 3$, $8 = 3 + 5$, etc.).

In mathematical notation, the Fibonacci numbers could be defined by recurrence as follows:

\[F_1 = 1, \;F_2 = 1, \;\;and\;\;  F_n = F_{n-1} + F_{n-2} \]
%
\begin{enumerate}

\item Write a program using a {\tt for} loop that prints on screen the first 20 Fibonacci numbers.

\item Write a program which prompts the user to enter a number
$n$ and, using a {\tt for} loop, computes and displays the
$n^{th}$ Fibonacci number.

\end{enumerate}

Solution: \ref{sol_fibonacci}

\end{exercise}

\begin{exercise}
\label{sub_recurse}
\index{recursion}

What is the output of the following program?
Draw a stack diagram that shows the state of the program
when it prints the result.

\begin{verbatim}[fontshape=up]
sub recurse($n, $s) {
    if ($n == 0) {
        say $s;
    } else {
        recurse $n - 1, $n + $s;
    }
}
recurse 3, 0;
\end{verbatim}

\begin{enumerate}

\item What would happen if you called this function like
this: {\tt recurse(-1, 0)}?

\item Write a documentation comment (maybe in the form of a multiline comment) that explains everything someone would need to know in order to use this function (and nothing else).

\end{enumerate}

Solution: \ref{sol_sub_recurse}

\end{exercise}


\chapter {Differentiating Polynomials}

\section{Differentiating polynomials}

If you had a function that gave you the height of an object, it would
be handy to be able to figure out a function that gave you the
velocity at which it was rising or falling. The process of converting
the position function into a velocity function is known as
\emph{differentiation} or \emph{finding the derivative}.

There are a bunch of rules for finding a derivative, but
differentiating polynomials only requires three:
\begin{itemize}
\item The derivative of a sum is equal to the sum of the derivatives.
\item The derivative of a constant is zero.
\item The derivative of a nonconstant monomial $at^b$ ($a$ and $b$ are constant numbers, $t$ is time) is $abt^{b-1}$
\end{itemize}\index{differentiation!polynomials}

So, for example, if I tell you that the height in meters of quadcopter
at second $t$ is given by $2t^3 - 5t^2 + 9t + 200$. You could tell me
that its vertical velocity is $6t^{2} - 10t + 9$

\begin{Exercise}[title={Differentation of polynomials}, label=diffpoly]
  Differentiate the following polynomials.
\end{Exercise}
\begin{Answer}[ref=diffpoly]
\end{Answer}
Notice that the degree of the derivative is one less than the degree
of the original polynomial. (Unless, of course, the degree of the
original is already zero.)

Now, if you know that a position is given by a polynomial, you can
differentate it to find the object's velocity at any time.

The same trick works for acceleration: Let's say you know a function
that gives an object's velocity. To find its acceleration at any time,
you take the derivative of the velocity function.

\begin{Exercise}[title={Differentation of polynomials in Python}, label=pydiffpoly]
  Write a function that returns the derivative of a polynomial in \filename{poly.py}. It should look like this:
\begin{Verbatim}
def derivative_of_polynomial(pn):
  ...Your code here...
\end{Verbatim}
When you test it in \filename{test.py}, it should look like this:
\begin{Verbatim}
# 3x**3 + 2x + 5
p1 = [5.0, 2.0, 0.0, 3.0]
d1 = poly.derivative_of_polynomial(p1)
# d1 should be 9x**2 + 2
print("Derivative of", poly.polynomial_to_string(p1),"is", poly.polynomial_to_string(d1))

# Check constant polynomials
p2 = [-9.0]
d2 = poly.derivative_of_polynomial(p2)
# d2 should be 0.0
print("Derivative of", poly.polynomial_to_string(p2),"is", poly.polynomial_to_string(d2))
\end{Verbatim}
\end{Exercise}
\begin{Answer}[ref=pydiffpoly]
\begin{Verbatim}
def derivative_of_polynomial(pn):

    # What is the degree of the resulting polynomial?
    original_degree = len(pn) - 1
    if original_degree > 0:
        degree_of_derivative = original_degree - 1
    else:
        degree_of_derivative = 0

    # We can ignore the constant term (skip the first coefficient)
    current_degree = 1
    result = []

    # Differentiate each monomial
    while current_degree < len(pn):
        coefficient = pn[current_degree]
        result.append(coefficient * current_degree)
        current_degree = current_degree + 1

    # No terms? Make it the zero polynomial
    if len(result) == 0:
        result.append(0.0)

    return result
\end{Verbatim}
\end{Answer}


\chapter{Functions}\label{ch:functions}

Several mathematical and string functions are implemented in
\aprepro{}.  To cause a function to be used, you enter the name
of the function followed by a list of zero or more arguments in
parentheses. For example
\begin{apinp}
\{sqrt(min(a,b*3))\}
\end{apinp}
uses the two functions \cmd{sqrt()} and \cmd{min()}. The arguments \cmd{a}
and \cmd{b*3} are passed to \cmd{min()}. The result is then passed as an
argument to \cmd{sqrt()}. The functions in \aprepro{} are listed below
along with the number of arguments and a short description of their effect.

\section{Mathematical Functions}

The following mathematical functions are available in \aprepro{}.

\begin{longtable}{lp{4.0in}}
\caption{Mathematical Functions}\label{t:functions}\\
Syntax              & Description \\
\hline
\endhead
abs(x)              &  Absolute value of $x$. $|x|$.\\
acos(x)             &  Inverse cosine of $x$, returns radians.\\
acosd(x)            &  Inverse cosine of $x$, returns degrees.\\
acosh(x)            &  Inverse hyperbolic cosine of $x$.\\
asin(x)             &  Inverse sine of $x$, returns degrees.\\
asin(x)             &  Inverse sine of $x$, returns radians.\\
asinh(x)            &  Inverse hyperbolic sine of $x$.\\
atan(x)             &  Inverse tangent of $x$, returns radians.\\
atan2(x,y)          &  Inverse tangent of $y/x$, returns radians.\\
atan2d(x,y)         &  Inverse tangent of $y/x$, returns degrees.\\
atand(x)            &  Inverse tangent of $x$, returns degrees.\\
atanh(x)            &  Inverse hyperbolic tangent of $x$.\\
ceil(x)             &  Smallest integer not less than $x$.\\
cos(x)              &  Cosine of $x$, with $x$ in radians\\
cosd(x)             &  Cosine of $x$, with $x$ in degrees\\
cosh(x)             &  Hyperbolic cosine of $x$.\\
d2r(x)              &  Degrees to radians.\\
dim(x,y)            &  $x - \min(x,y)$\\
dist(x1,y1, x2,y2)  &  $\sqrt{(x_1-x_2)^2 + (y_1-y_2)^2}$ \\
exp(x)              &  Exponential  $e^x$ \\
find\_word(word,svar,del)&  Find 1-based index of \var{word} in \var{svar}. Words are separated by one or more of the characters in the string variable del. Returns 0 if \var{word} is not found.\\
floor(x)            &  Largest integer not greater than $x$.\\
fmod(x,y)           &  Floating-point remainder of $x/y$.\\
hypot(x,y)          &  $\sqrt{x^2+y^2}$.\\
int(x), [x]         &  Integer part of $x$ truncated toward 0.\\
julday(mm, dd, yy)  &  Julian day corresponding to mm/dd/yy. \\
juldayhms(mm, dd, yy, hh, mm, ss)&  Julian day corresponding to mm/dd/yy at hh:mm:ss \\
lgamma(x)           &  $\log(\Gamma(x))$.\\
ln(x)               &  Natural (base e) logarithm of $x$.\\
log(x)              &  Natural (base e) logarithm of $x$.\\
log10(x)            &  Base 10 logarithm of $x$. \\
log1p(x)            &  $log(1+x)$ Accurate even for very small values of $x$\\
max(x,y)            &  Maximum of $x$ and $y$. \\
min(x,y)            &  Minimum of $x$ and $y$. \\
nint(x)             &  Rounds $x$ to nearest integer. $<0.5$ down; $>=0.5$ up.\\
polarX(r,a)         &  $r * \cos(a)$, $a$ is in degrees \\
polarY(r,a)         &  $r * \sin(a)$, $a$ is in degrees \\
r2d(x)              &  Radians to degrees. \\
rand(xl,xh)         &  Random value between $xl$ and $xh$; uniformly distributed. \\
rand\_lognormal(m,s)&  Random value with lognormal distribution with mean $m$ and stddev $s$.\\
rand\_normal(m,s)   &  Random value normally distributed with mean $m$ and stddev $s$.\\
rand\_weibull(a, b) &  Random value with weibull distribution with $\alpha=a$ and $\beta=b$. \\
sign(x,y)           &  $x * \text{sgn}(y)$\\
sin(x)              &  Sine of $x$, with $x$ in radians. \\
sind(x)             &  Sine of $x$, with $x$ in degrees. \\
sinh(x)             &  Hyperbolic sine of $x$ \\
sqrt(x)             &  Square root of $x$. $\sqrt{x}$\\
srand(seed)         &  Seed the random number generator with the given integer value. At the beginning of \aprepro{} execution, \cmd{srand()}
                       is called with the current time as the seed. \\
strtod(svar)        &  Returns a double-precision floating-point number equal to the value represented by the character string pointed to by \var{svar}.\\
tan(x)              &  Tangent of $x$, with $x$ in radians. \\
tand(x)             &  Tangent of $x$, with $x$ in radians. \\
tanh(x)             &  Hyperbolic tangent of $x$. \\
Vangle(x1,y1,x2,y2) &  Angle (radians) between vector $x_1\hat{i}+y_1\hat{j}$ and $x_2\hat{i}+y_2\hat{j}$.\\
Vangled(x1,y1,x2,y2)&  Angle (degrees) between vector $x_1\hat{i}+y_1\hat{j}$ and $x_2\hat{i}+y_2\hat{j}$.\\
word\_count(svar,del)&  Number of words in \var{svar}. Words are separated by one or more of the characters in the string variable del.\\
\hline
\end{longtable}

\begin{longtable}{lp{4.0in}}
\caption{String Functions}\label{t:stringfunctions}\\
Syntax              & Description \\
\hline
\endhead
DUMP()              &  Output a list of all defined variables and their value. \\
DUMP\_FUNC()        &  Output a list of all double and string functions recognized by \aprepro{}. \\
DUMP\_PREVAR()      &  Output a list of all predefined variables and their value. \\
IO(x)               &  Convert x to an integer and then to a string. Can be used to output integer values if your output format (\cmd{\_FORMAT}) is set to something that doesn't output integers correctly.  \\
Units(svar)         &  See Chapter~\ref{ch:units}. \var{svar} is one of the defined units systems: 'si', 'cgs', 'cgs-ev', 'shock', 'swap', 'ft-lbf-s', 'ft-lbm-s', 'in-lbf-s' \\
error(svar)         &  Outputs the string \var{svar} to stderr and then terminates the code with an error exit status. \\
execute(svar)       &  \var{svar} is parsed and executed as if it were a line read from the input file. \\
exodus\_info(filename, prefix) & Open the \exo{} file and return a
string which is the concatenation of all \exo{} info lines that begin
with ``prefix''. The prefix is stripped from the line. \\
exodus\_info(filename, begin, end) & Open the \exo{} file and return a
string which is the concatenation of all \exo{} info lines following
the line that matches ``begin'' up to the line that matches ``end''. \\
exodus\_meta(filename) & Open the \exo{} file and create several variables based on the metadata in the \exo{} file. \\
extract(s, b, e)    &  Return substring \var{[b,e)}. \var{b} is included; \var{e} is not. If \var{b} not found, return empty; If \var{e} not found, return rest of string. If \var{b} empty, start at beginning; if \var{e} empty, return rest of string. \\
file\_to\_string(fn)&  Opens the file specified by \var{fn} and returns the contents as a multi-line string. \\
get\_date()         &  Returns a string representing the current date in the form YYYY/MM/DD. \\
get\_iso\_date()    &  Returns a string representing the current date in the form YYYYMMDD. \\
get\_time()         &  Returns a string representing the current time in the form HH:MM:SS. \\
get\_word(n,svar,del&  Returns a string containing the \var{n}th word of \var{svar}. The words are separated by one or more of the characters in the string variable \var{del}  \\
getenv(svar)        &  Returns a string containing the value of the environment variable \var{svar}. If the environment variable is not defined, an empty string is returned.  \\
help()              &  Tell how to get help on variables, functions, \ldots \\
include\_path(path) &  Specify an optional path to be prepended to a filename when opening a file. Can also be specified via the \cmd{-I} command line option when executing aprepro. \\
output(filename)    &  Creates the file specified by filename and
sends all subsequent output from aprepro to that file. Calling \cmd{output(\"stdout\")} will close the current output file and return output to the terminal (standard output).\\
output\_append(fn)  &  If file with name \var{fn} exists, append output to it; otherwise create the file and send all subsequent output from aprepro to that file. \\
rescan(svar)        &  The difference between \cmd{execute(sv1)} and \cmd{rescan(sv2)} is that \var{sv1} must be a valid expression, but \var{sv2} can contain zero or more expressions.  \\
to\_lower(svar)     &  Translates all uppercase characters in \var{svar} to lowercase. It modifies \var{svar} and returns the resulting string.   \\
tolower(svar)       &  Translates all uppercase characters in \var{svar} to lowercase. It modifies \var{svar} and returns the resulting string.   \\
to\_string(x)       &  Returns a string representation of the numerical variable \var{x}. The variable \var{x} is unchanged.  \\
tostring(x)         &  Returns a string representation of the numerical variable \var{x}. The variable \var{x} is unchanged.  \\
to\_upper(svar)     &  Translates all lowercase character in \var{svar} to uppercase. It modifies \var{svar} and returns the resulting string.  \\
toupper(svar)       &  Translates all lowercase character in \var{svar} to uppercase. It modifies \var{svar} and returns the resulting string.  \\
\hline
\end{longtable}

The following example shows the use of some of the string functions. The input:
\begin{apinp}
\{t1 = "ATAN2"\}
\{t2 = "(0, -1)"\}
\{t3 = tolower(t1//t2)\}
\{execute(t3)\}
\end{apinp}
produces the output:
\begin{apout}
ATAN2
(0, -1)
atan2(0, -1)   \textit{The variable t3 is equal to the string atan2(0,-1)}
3.141592654    \textit{The result is the same as executing \{atan2(0, -1)\}}
\end{apout}

This is admittedly a very contrived example; however, it does
illustrate the workings of several of the functions. In the example,
an expression is constructed by concatenating two strings together and
converting the resulting string to lowercase.  This string is then
executed and simply prints the result of evaluating the expression.

The following example uses the \cmd{rescan} function to illustrate a basic
macro capability in \aprepro{}. The example calculates the coordinates
of eleven points (Point1 \ldots{} Point11) equally spaced about the
circumference of a 180 degree arc of radius 10.

\begin{apinp}
\{ECHO(OFF)\}\
\{num = 0\}
\{rad = 10\}
\{nintv = 10\}
\{nloop = nintv + 1\}
\{line = 'Define \{"Point"//tostring(++num)\}, \{polarX(rad, (num-1) *
  180/nintv)\} \{polarY(rad, (num-1)*180/nintv)\}'\}
\{ECHO(ON)\}
\{loop(nloop)\}
\{rescan(line)\}
\{endloop\}
\end{apinp}

Output:

\begin{apout}
Define  Point1,  10    0
Define  Point2,  9.510565163    3.090169944
Define  Point3,  8.090169944    5.877852523
Define  Point4,  5.877852523    8.090169944
Define  Point5,  3.090169944    9.510565163
Define  Point6,  6.123233765e-16    10
Define  Point7,  -3.090169944    9.510565163
Define  Point8,  -5.877852523    8.090169944
Define  Point9,  -8.090169944    5.877852523
Define  Point10,  -9.510565163    3.090169944
Define  Point11,  -10    1.224646753e-15
\end{apout}

Note the use of the \cmd{ECHO(OFF\textbar{}ON)} block to
suppress output during the initialization phase, and the loop construct
to automatically repeat the rescan line. The variable \cmd{num} is converted
to a string after it is incremented and then concatenated to build the name of
the point. In the definition of the variable \cmd{line}, single quotes are first
used since this is a multi-line string; double quotes are then used to embed another
string within the first string. To modify this example to calculate the coordinates
of 101 points rather than eleven, the only change necessary would be to set \cmd{\{nintv=100\}}.

\section{Additional Functions }

\subsection{[{\em var}] or [{\em expression}]} Surrounding a variable or expression
by square brackets will return the integer value of that variable or
expression truncated toward zero. For example \cmd{[sqrt(2)]} will return the value
\cmd{1}.

\subsection{File Inclusion} \aprepro{} can read input from multiple
files using the \cmd{include()} and \cmd{cinclude()} functions. If a line
of the form:

\cmd{\{include(\texttt{"}\textit{filename}\texttt{"})\}}\\
\cmd{\{include(string\_variable)\}}

is read, \aprepro{} will open and begin reading from the file
\file{filename}.  A string variable can be used as the
argument instead of a literal string value.  When the end of the file
is reached, it will be closed and \aprepro{} will continue
reading from the previous file. The difference between
\cmd{include()} and \cmd{cinclude()} is that if
\file{filename} does not exist, \cmd{include()} will
terminate \aprepro{} with a fatal error, but \cmd{cinclude()} will just
write a warning message and continue with the current file. The
\cmd{cinclude()} function can be thought of as a {\em conditional
include}, that is, include the file if it exists. Multiple include
files are allowed and an included file can also include additional
files. This option can be used to set variables globally in several
files. For example, if two or more input files share common points or
dimensions, those dimensions can be set in one file that is included
in the other files.

If \cmd{ECHO(OFF)} is in effect during in an included file, \cmd{ECHO(ON)}
will automatically be executed at the end of the included file.

\subsection{Conditionals} Portions of an input file can be conditionally processed
through the use of the \cmd{if(expression)}, \cmd{elseif(expression)}, \cmd{else}, and \cmd{endif}
construct.\footnote{The \cmd{Ifdef(expression)} and \cmd{Ifndef(expression)} construct is deprecated. Please use \cmd{if(expression)} and \cmd{if(!expression)} instead.}
The syntax is:

\begin{apinp}
\{if(expression)\}
\ldots Lines processed if 'expression' is true or non-zero.
\{elseif(expression2)\}
\ldots Lines processed if 'expression' is false and 'expression2' is true.
\{else\}
\ldots Lines processed if both 'expression' and 'expression2' are false.
\{endif\}
\end{apinp}

The \cmd{elseif()} and \cmd{else} are optional.  Note that if \var{expression} is a simple \var{variable}, then its value will be zero or false if it is undefined; a zero value evaluates to false and a non-zero value is true. The \cmd{if} construct can be nested multiple levels.
A warning message will be printed if improper nesting is detected. The \cmd{if(expression)},
\cmd{elseif(expression)}, \cmd{else}, and \cmd{endif} are the
only text parsed on a line. Text that follows these on the same line is
ignored.  For example:

\begin{apinp}
\{if(a > 10 && b < 10)\} This will be ignored no matter what
\ldots Lines processed if \var{a} > 10 and \var{b} < 10.
\{endif\}
\end{apinp}

\subsection{Switch Statements}
The \cmd{switch} statement is a control construct which allows the value of a variable or expression to change the control flow via a multi-way branch.
The construct is begun with a \cmd{switch(expression)} statement followed by one or more \cmd{case(expression)} statements and an optional \cmd{default} statement. The construct is ended with an \cmd{endswitch} statement.  The expression in the \cmd{switch(expression)} statement is evaluated and compared to each \cmd{case(expression)} statement in order.  If the values of the two expressions are equal, then the code following that \cmd{case(expression)} is evaluated up to the next \cmd{case()} or \cmd{default} statement. If the expressions in more than one \cmd{case()} match the initial \cmd{switch()} expression, only the first one will be activated.  If none of the \cmd{case()} expressions match the \cmd{switch()} expression, then the code following the \cmd{default} command will be evaluated. An example of the syntax is:

\begin{apinp}
\{a = 10*PI\}
\{switch(10*PI + sin(0))\}
\ldots This is ignored since it is after the switch, but before any \cmd{case()} statements
\{case(1)\}
\ldots This is not executed since \var{1} is not equal to \var{10*PI+sin(0)}
\{case(a)\}
\ldots This is executed since \var{a} matches the value of \var{10*PI+sin(0)}
\{case(10*PI+sin(0))\}
\ldots This is not executed since a previous case was executed.
\{default\}
\ldots This is not executed since a previous case was executed.
\{endswitch\}
\ldots This is executed since the switch construct
 is finished.
\end{apinp}

Switch constructs cannot be nested, but a \cmd{switch()} can be used inside an \cmd{if()} construct and an \cmd{if()} can be used inside a \cmd{case()} construct.
The \cmd{switch(expression)}, \cmd{case(expression)}, \cmd{default}, and \cmd{endswitch} are the only text parsed on a line. Text that follows these on the same line is
ignored.

\subsection{Loops} Repeated processing of a group of lines can be controlled
with the \cmd{loop(control)}, and \cmd{endloop} commands. The syntax is:
\begin{apinp}
\{loop(variable)\}
\ldots Process these lines \var{variable} times
\{endloop\}
\end{apinp}

Loops can be nested. A numerical variable or constant must be specified as the
loop control specifier. You cannot use an algebraic expression such as

\cmd{\{loop(3+5)\}}.

The \cmd{endloop} command must be on a line by itself with no other text except optional whitespace (spaces or tabs).

\subsection{ECHO}\label{echo} The printing of lines to the output file can be controlled
through the use of the \cmd{ECHO(OFF)} and \cmd{ECHO(ON)}
commands. The syntax is:

\begin{apinp}
\{ECHO(OFF)\}
\ldots These lines will be processed, but not printed to output
\{ECHO(ON)\}
\ldots These lines will be both processed and printed to output.
\end{apinp}

\cmd{ECHO} will automatically be turned on at the end of an included file. The
commands \cmd{ECHO} and \cmd{NOECHO} are synonyms for \cmd{ECHO(ON)} and \cmd{ECHO(OFF)}.

\subsection{VERBATIM} The printing of all lines to the output file without processing
can be controlled through the use of the \cmd{VERBATIM(ON)} and \cmd{VERBATIM(OFF)}
commands. The syntax is:

\begin{apinp}
\{VERBATIM(ON)\}
\ldots These lines will be printed to output, but not processed
\{VERBATIM(OFF)\}
\ldots These lines will be printed to output and processed
\end{apinp}
NOTE:  there  is  a  major  difference  between  the  \cmd{ECHO/NOECHO} commands,
the \cmd{Ifdef/Endif }commands, and the \cmd{VERBATIM(ON\textbar{}OFF)} commands:

\begin{itemize}
\item \cmd{ECHO(ON\textbar{}OFF)} Lines processed, but not printed if \cmd{ECHO(OFF)}
\item \cmd{Ifdef/Endif} Lines not processed or printed if in \cmd{Ifndef} block
\item \cmd{VERBATIM(ON\textbar{}OFF)} Lines not processed, but are printed.
\end{itemize}

\subsection{IMMUTABLE}\label{immutable_block} Variables can either be
created as mutable or immutable.  By default, all variables created
during a run of aprepro are mutable unless the \cmd{--immutable} or
\cmd{-X} command line option is used to execute \aprepro{}.  An
\cmd{IMMUTABLE} block can also be used to change \aprepro{} such that
all variables are created as immutable.  The syntax is:
\begin{apinp}
\{IMMUTABLE(ON)\}
\ldots All variables created will be immutable
\{IMMUTABLE(OFF)\}
\ldots The mutable/immutable state changes back to the default which
is typically mutable unless \aprepro{} executed with the
\cmd{--immutable} or \cmd{-X} options.
\end{apinp}
Note that any variables created as immutable are still immutable
following the \cmd{IMMUTABLE(OFF)} command.

\subsection{Output File Specification} The \cmd{output} function can be used
to change the file to which \aprepro{} is outputting the processed
data.  The syntax is: \cmd{\{output("\file{filename}")\}}, where
\file{filename} is the name of the new output file. A string variable
can be used as the function argument. The previous output file is
closed. An error message is written and the code terminates if the
file cannot be opened. If \cmd{output("\file{stdout}")} is specified,
then the current output file is closed and output is again written to
the standard output which is where output is written by default.

\subsection{\exo{} Metadata Extraction} \aprepro{} can parse the
metadata from a binary \exo{}~\cite{exodus} file and create several
variables which can then be used for calculations or decisions.  The
function syntax is \cmd{exodus\_meta(filename)}. The
argument to the function is a string containing the filename of the
Exodus file.  If the file does not exist in the current directory,
\aprepro{} will prepend the path specified by the \cmd{--include} or
\cmd{-I} command line option.

The following scalar variables will be defined:

\begin{longtable}{lp{4.0in}}
\caption{\exo{} Scalar Variables}\\
Variable              & Description \\
\hline
\endhead
ex\_dimension        & Spatial dimension \\
ex\_node\_count      & Number of nodes \\
ex\_element\_count   & Number of elements \\
ex\_block\_count     & Number of element blocks \\
ex\_sideset\_count   & Number of sidesets \\
ex\_nodeset\_count   & Number of nodesets \\
ex\_timestep\_count  & Number of timesteps \\
ex\_version          & Version of the \exo{} database \\
\hline
\end{longtable}

The following string variables will be defined if the model contains
one or more of the specific entity type.  The strings will be a
comma-separated concatenation of the names of the entity.  The
\cmd{get\_word} function can be used to extract a specific sub-string.

\begin{longtable}{lp{4.0in}}
\caption{\exo{} String Variables}\\
Variable              & Description \\
\hline
\endhead
ex\_title            & The title of the database \\
ex\_block\_names     & Element Block names.  Will be ``block\_'' +
block id if no names on the database. \\
ex\_block\_topology  & The topology of the element blocks.  Converted
to all lowercase. \\
ex\_sideset\_names   & Sideset names.  Will be ``sideset\_'' + sideset
id if no names on the database. \\
ex\_nodeset\_names   & Nodeset names.  Will be ``nodeset\_'' + nodeset
id if no names on the database. \\
\hline
\end{longtable}

The following array variables will be defined if the model contains
one or more of the specific entity type.

\begin{longtable}{lccp{4.0in}}
\caption{\exo{} Array Variables}\\
Variable              & Rows  & Columns & Description \\
\hline
\endhead
ex\_block\_ids	      & ex\_block\_count & 1 & Element Block Ids. \\
ex\_block\_info	      & ex\_block\_count & 4 & Element Block info:
id, number of elements in block, number of nodes per element, number
of attributes. \\
ex\_sideset\_ids      & ex\_sideset\_count & 1 & Sideset Ids. \\
ex\_sideset\_info     & ex\_sideset\_count & 3 & Sideset info: id,
number of faces in sideset, number of distribution factors. \\
ex\_nodeset\_ids      & ex\_nodeset\_count & 1 & Nodeset Ids. \\
ex\_nodeset\_info     & ex\_nodeset\_count & 3 & Nodeset info: id,
number of nodes in nodeset, number of distribution factors. \\
ex\_timestep\_times   & ex\_timestep\_count & 1 & Timestep times. \\
\hline
\end{longtable}

The following shows an example of the variables which are defined:

\begin{apinp}
  {exodus\_meta("filename.e")}
  {DUMP()}
  Element Block IDs:
  {print\_array(transpose(ex\_block\_ids))}

  Element Block Info: (id, num, nnpe, nattrib)
  {print\_array(ex\_block\_info)}
\end{apinp}

\begin{apout}
$   Variable    = Value
$  {ex\_block\_count	= 8}
$  {ex\_nodeset\_ids	 (array) rows = 6, cols = 1}
$  {ex\_block\_names	= "block\_8,block\_7,block\_6,block\_5,block\_4,block\_3,block\_2,block\_1"}
$  {ex\_block\_topology	= "hex,hex,hex,hex,hex,hex,hex,hex"}
$  {ex\_nodeset\_info	 (array) rows = 6, cols = 3}
$  {ex\_sideset\_count	= 0}
$  {ex\_dimension	= 3}
$  {ex\_element\_count	= 64}
$  {ex\_nodeset\_names	= "nodeset\_10,nodeset\_100,nodeset\_20,nodeset\_200,nodeset\_30,nodeset\_300"}
$  {ex\_nodeset\_count	= 6}
$  {ex\_block\_ids	 (array) rows = 8, cols = 1}
$  {ex\_block\_info	 (array) rows = 8, cols = 4}
$  {ex\_timestep\_times	 (array) rows = 11, cols = 1}
$  {ex\_version	= 2.029999971}
$  {ex\_timestep\_count	= 11}
$  {ex\_title  	= "Sierra output: dummy title"}
$  {ex\_node\_count	= 125}

Element Block IDs:
	8	7	6	5	4	3	2	1

Element Block Info: (id, num, nnpe, nattrib)
	8	8	8	0
	7	8	8	0
	6	8	8	0
	5	8	8	0
	4	8	8	0
	3	8	8	0
	2	8	8	0
	1	8	8	0
\end{apout}

\subsection{\exo{} Info Records Extraction} \aprepro{} can extract all
or a portion of the ``information records'' from a binary \exo{} file
and return the results as a string variable.

There are two forms of the function.  The first function has the
syntax:  \cmd{exodus\_info(filename, prefix)}.  This will read
the information records from the \exo{} database specified by the
string variable \var{filename} and search for lines
that begin with the specified \var{prefix}.  If a line is found, the
\var{prefix} will be stripped from the line and the remaining
characters on the line will be concatenated onto the return string
followed by a newline character.

The second function has the syntax: \cmd{exodus\_info(filename, begin, end)}.
This will read the information records from the \exo{} database
specified by the string variable \var{filename} and search for a line
that matches the string variable \var{begin}.  It will then append all
subsequent information lines onto the return string until a line that
matches the string variable \var{end} or it reaches the end of the
information records.  If there is another line matching \var{begin},
it will resume appending lines to the return string.

The returned string can then be operated on as a normal \aprepro{}
variable.


\problemname{Arithmetic Decoding}

Arithmetic coding is a method to represent a message as a real number
$x$ such that $0 \leq x < 1$. We will assume that the
message consists only of uppercase `A's and `B's.  The two letters
have associated probabilities $p_A$ and $p_B = 1 - p_A$ such that
$0 < p_A < 1$.

The current interval $[a,b)$ is initially set to $[0,1)$ and we will
update this interval one letter at a time.  To encode
a letter, the current interval is divided into two subintervals
as follows.  Let $c = a + p_A(b-a)$.  If the next letter is `A',
$[a,c)$ becomes the current interval.  Otherwise, the current interval
is now $[c,b)$.  This process is repeated for each letter in the
message.  If $[k,\ell)$ is the final interval, the encoded message is
chosen to be $k$.

For example, if the original message is ``ABAB'' and $p_A = p_B = 0.5$,
the sequence of intervals encountered in the algorithm is
\[ [0,1) \xrightarrow{A} [0, 0.5) \xrightarrow{B} [0.25, 0.5)
  \xrightarrow{A} [0.25, 0.375) \xrightarrow{B} [0.3125, 0.375). \]
The encoded message is therefore 0.3125, or 0.0101 in binary.

Given the length of the message, the probabilities, and the encoded
message, determine the original message.

\section*{Input}

The first line contains the integer $N$ ($1 \leq N \leq 15$), which
is the length of the original message.  The
second line contains the integer $D$ ($1 \leq D \leq 7$),
which indicates that $p_A = \frac{D}{8}$.
The third line contains the binary representation of the encoded message.
It is guaranteed that the binary representation of the encoded message
starts with ``0.'' and contains at most $3N+2$ characters.

It is guaranteed that the encoded message came from an initial message
of length $N$ consisting only of `A' and `B' using this value of $p_A$.

\section*{Output}

Display the original message.


\section{Indefinite Integrals \& Ways to Solve Them}

\subsection{Definition of an Indefinite Integral}
We've seen in the previous section from the Fundamental Theorem of Calculus how we can let the upper bound of a definite integral be a variable, giving us a new function that is an antiderivative of the function being integrated.
Anti-differentiation is a useful operation, so notationally we drop the bounds from the definite integral, which we call an indefinite integral.
\begin{definition}
	The indefinite integral of some continuous function $f$ is
	\begin{equation*}
		\int{f(x)\d{x}} = \int_{a}^{x}{f(t)\d{t}} = F(x) - F(a) = F(x) + C,
	\end{equation*}
	where $F(x)$ is the antiderivative of $f$.
\end{definition}

Rather than choose a particular value for $C$, we just write ``$+C$'' when integrating to capture all antiderivatives.
Note that since we defined an indefinite integral in terms of a definite integral, all the basic properties of definite integrals still apply.

\begin{example}
	Solve the following indefinite integral:
	\begin{equation*}
		\int{\cos{x}\d{x}}.
	\end{equation*}
\end{example}
\begin{answer}
	We derived previously that the derivative of $\sin{x}$ is $\cos{x}$.
	So, for any real constant $C$, $\sin{x} + C$ is the antiderivative of $\cos{x}$.
	\begin{equation*}
		\int{\cos{x}\d{x}} = \sin{x} + C.
	\end{equation*}
\end{answer}

\subsection{Indefinite Integrals Properties \& Strategies}
Knowing that the indefinite integral give us the antiderivative, we can simply apply the rules we derived for derivatives in reverse.

\subsubsection{Power Rule \& Integral of $1/x$}
\begin{lemma}
	Let $n \neq -1$ be a real number.
	Then
	\begin{equation*}
		\int{x^n \d{x}} = \frac{x^{n+1}}{n+1} + C.
	\end{equation*}
\end{lemma}

$n = -1$ has to be a special case, otherwise the denominator would be 0. \\

We derived earlier that that the derivative of $\ln{x}$ was $1/x$.
However, we have to be a little more careful before we write the integral of $1/x$.
$1/x$ is defined for all real values except 0, but $\ln{x}$ is only defined for positive values.
So, we need a different antiderivative, which would have to be equal to $\ln{x}$ for positive $x$, that's defined everywhere that $1/x$ is defined.
$\ln{\abs{x}}$ works nicely because it's defined everywhere that $1/x$ is defined, it's the antiderivative for positive $x$, and its slope for negative values of $x$ corresponds exactly to how $1/x$ is negative for negative values of $x$.
\begin{lemma}
	\begin{equation*}
		\int{\frac{1}{x}\d{x}} = \ln{\abs{x}} + C.
	\end{equation*}
\end{lemma}

\subsubsection{Exponential Rule}
Since $e^x$ is its own derivative, it's also its own antiderivative.
A similar idea applies for any base.
\begin{lemma}
	\begin{equation*}
		\int{b^x\d{x}} = \frac{b^x}{\ln{b}} + C.
	\end{equation*}
\end{lemma}

\input{./integrals/usub.tex}
\input{./integrals/integration_by_parts/integration_by_parts.tex}