\chapter{Fruitful subroutines}
\label{fruitchap}

Most of the Perl functions we have used, such as the math
functions, produce return values.  But most of the subroutines
we've written so far are void: they have an effect, like printing
a value, but they don't have a return value.  In
this chapter you will learn to write fruitful functions.

\section{Return values}
\index{return!value}

Calling a fruitful function generates a return
value, which we usually assign to a variable or use as part of an
expression.

\begin{verbatim}
my $pi = 4 * atan 1;
my $height = $radius * sin $radians;
\end{verbatim}
%
Many of the subroutines we have written so far are void.
Speaking casually,
they have no usable return value; more precisely,
their return value may be {\tt Any}, {\tt ()} or {\tt True}.

In this chapter, we are (finally) going to write fruitful subroutines.
The first example is {\tt area}, which returns the area of a circle
with the given radius:

\begin{verbatim}
sub area($radius) {
    my $circular_area = pi * $radius**2;
    return $circular_area;
}
\end{verbatim}
%
We have seen the {\tt return} statement before, but in a fruitful
function the {\tt return} statement includes
an expression.  This statement means: ``Return immediately from
this function and use the following expression as a return value.''
The expression can be arbitrarily complicated, so we could
have written this function more concisely:
\index{return!statement}
\index{statement!return}

\begin{verbatim}
sub area($radius) {
    return pi * $radius**2;
}
\end{verbatim}
%
On the other hand, {\bf temporary variables} like
\verb'$circular_area' can make debugging easier. They
may also help document what is going on.
\index{temporary variable}
\index{variable!temporary}

Sometimes it is useful to have multiple return statements, for
example one in each branch of a conditional:

\begin{verbatim}
sub absolute_value($num){
    if $num < 0 {
        return -$num;
    } else {
        return $num;
    }
}
\end{verbatim}
%
Since these {\tt return} statements are in an alternative
conditional, only one runs.

This could also be written more concisely using the statement
modifier syntax:

\begin{verbatim}
sub absolute_value($num){
    return -$num if $num < 0;
    return $num;
}
\end{verbatim}
%
Here again, only one of the return statements runs: if the
number is negative, the first return statement is executed and
the subroutine execution stops there; if the number is
positive or zero, then only the second return statement is
executed.

As soon as a return statement runs, the function
terminates without executing any subsequent statements.
Code that appears after an unconditional {\tt return} statement,
or any other place the flow of execution can never reach,
is called {\bf dead code}.
\index{dead code}

In a fruitful function, it is a good idea to ensure
that every possible path through the program hits a
{\tt return} statement.  For example:

\begin{verbatim}
sub absolute_value($num){
    if $num < 0 {
        return -$num;
    }
    if $num > 0 {
        return $num;
    }
}
\end{verbatim}
%

This subroutine is incorrect because if {\tt \$num} happens to be 0,
neither condition is true, and the subroutine ends without hitting a
{\tt return} statement.  If the flow of execution gets to the end
of a function, the return value is {\tt ()}, which basically
means ``not defined'' and is clearly not the absolute value of 0.
\index{undefined value}

\begin{verbatim}
> absolute_value(0)
()
\end{verbatim}
%
By the way, Perl provides a built-in function called
{\tt abs} that computes absolute values.
\index{abs function or method}
\index{function!abs}

\label{compare}
As an exercise, write a {\tt compare} subroutine that
takes two numbers, {\tt \$x} and {\tt \$y}, and returns {\tt 1}
if {\tt \$x > \$y}, {\tt 0} if {\tt \$x == \$y}, and
{\tt -1} if {\tt \$x < \$y}.
Solution: \ref{sol_compare}
\index{compare function}
\index{function!compare}

\section{Incremental development}
\label{incremental.development}
\index{development plan!incremental}
\index{incremental development}

As you write larger functions, you might find yourself
spending more time debugging.

To deal with increasingly complex programs,
you might want to try a process called
{\bf incremental development}.  The goal of incremental development
is to avoid long debugging sessions by adding and testing only
a small amount of code at a time.
\index{testing!incremental development}
\index{Pythagorean theorem}

As an example, suppose you want to find the distance between
twopoints, given by the Cartesian or rectangular coordinates
$(x_1, y_1)$ and $(x_2, y_2)$. By the Pythagorean theorem,
the distance is:
\index{Pythagorean theorem}
\index{Cartesian coordinates}
\index{coordinates!Cartesian}
\index{rectangular!coordinates}
\index{coordinates!rectangular}

\begin{displaymath}
\mathrm{distance} = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}
\end{displaymath}
%
The first step is to consider what a {\tt distance} function should
look like in Perl.  In other words, what are the inputs (parameters)
and what is the output (return value)?

In this case, the inputs are two points, which you can represent
using four numbers.  The return value is the distance represented by
a numeric value.

Immediately you can write an outline of the function:

\begin{verbatim}
sub distance($x1, $y1, $x2, $y2) {
    return 0.0;
}
\end{verbatim}
%
Obviously, this version doesn't compute distances; it always returns
zero.  But it is syntactically correct, and it runs, which means that
you can test it before you make it more complicated.

To test the new function, call it with sample arguments:

\begin{verbatim}
> distance(1, 2, 4, 6);
0.0
\end{verbatim}
%
I chose these values so that the horizontal distance is 3 and the
vertical distance is 4; that way, the result is 5, the hypotenuse
of a 3-4-5 triangle. When testing a function, it is
useful to know the right answer.
\index{testing!knowing the answer}

At this point we have confirmed that the function is syntactically
correct, and we can start adding code to the body.
A reasonable next step is to find the differences
$x_2 - x_1$ and $y_2 - y_1$.  The next version stores those values in
temporary variables and prints them.

\begin{verbatim}
sub distance($x1, $y1, $x2, $y2) {
    my $dx = $x2 - $x1;
    my $dy = $y2 - $y1;
    say '$dx is', $dx;
    say '$dy is', $dy;
    return 0.0;
}
\end{verbatim}
%
If the function is working, it should display \verb"$dx is 3" and
\verb"$dy is 4" (and still return 0.0).  If so, we know that the
function is getting the right arguments and performing the
first computation correctly.  If not, there are only a few lines
to check.

Next we compute the sum of squares of {\tt \$dx} and {\tt \$dy}:

\begin{verbatim}
sub distance($x1, $y1, $x2, $y2) {
    my $dx = $x2 - $x1;
    my $dy = $y2 - $y1;
    my $dsquared = $dx**2 + $dy**2;
    say '$dsquared is: ', $dsquared;
    return 0.0;
}
\end{verbatim}
%
Again, you would run the program at this stage and check the output
(which should be 25).
Finally, you can use the {\tt sqrt} built-in function to compute
and return the result:
\index{sqrt function}
\index{function!sqrt}

\begin{verbatim}
sub distance($x1, $y1, $x2, $y2) {
    my $dx = $x2 - $x1;
    my $dy = $y2 - $y1;
    my $dsquared = $dx**2 + $dy**2;
    my $result = sqrt $dsquared;
    return $result;
}
\end{verbatim}
%
If that works correctly, you are done.  Otherwise, you might
want to print the value of {\tt \$result} before the return
statement.

The final version of the subroutine doesn't display anything when it
runs; it only returns a value.  The {\tt print} statements we wrote
are useful for debugging, but once you get the function working, you
should remove them.  Code like that is sometimes called
{\bf scaffolding} because it is helpful for building the program
but is not part of the final product.
\index{scaffolding}

When you start programming, you should add only a line or two of code at a
time.  As you gain more experience, you might find yourself writing
and debugging bigger chunks.  Either way, incremental development
can save you a lot of debugging time.

The key aspects of the process are:

\begin{enumerate}

\item Start with a working program and make small incremental changes.
At any point, if there is an error, you should have a good idea
where it is.

\item Use variables to hold intermediate values so you can
display and check them.

\item Once the program is working, you might want to remove some of
the scaffolding or consolidate multiple statements into compound
expressions, but only if doing so does not make the program
difficult to read.

\end{enumerate}

Note that, at least for relatively simple cases, you can also
use the REPL to test expressions and even multi-line statements
or subroutines in interactive mode before you commit them to your
program code. This is usually fast and can save you some time.
\index{REPL}
\index{interactive mode}

\label{hypotenuse}
As an exercise, use incremental development to write a function
called {\tt hypotenuse} that returns the length of the hypotenuse of a
right triangle given the lengths of the other two legs as arguments.
Record each stage of the development process as you go.
Solution: \ref{sol_hypotenuse}.
\index{hypotenuse}

\section{Composition}
\index{composition}
\index{function composition}

As you should expect by now, you can call one function from within
another.  As an example, we'll write a function that takes two points,
the center of the circle and a point on the perimeter, and computes
the area of the circle.

Assume that the center point is stored in the variables {\tt \$x-c} and
{\tt \$y-c}, and the perimeter point is in {\tt \$x-p} and {\tt \$y-p}. The
first step is to find the radius of the circle, which is the distance
between the two points.  We just wrote a function, {\tt
distance}, that does that:

\begin{verbatim}
my $radius = distance($x-c, $y-c, $x-p, $y-p);
\end{verbatim}
%
The next step is to find the area of a circle with that radius;
we just wrote that, too:

\begin{verbatim}
my $result = area($radius);
\end{verbatim}
%
Encapsulating these steps in a function, we get:
\index{encapsulation}

\begin{verbatim}
sub circle-area($x-c, $y-c, $x-p, $y-p) {
    my $radius = distance($x-c, $y-c, $x-p, $y-p);
    my $result = area($radius)
    return $result;
}
\end{verbatim}
%
The temporary variables {\tt \$radius} and {\tt \$result} are useful for
development and debugging, but once the program is working, we can
make it more concise by composing the function calls:

\begin{verbatim}
sub circle-area($x-c, $y-c, $x-p, $y-p) {
    return area distance($x-c, $y-c, $x-p, $y-p);
}
\end{verbatim}
%

The last line of the previous example now works like a data
pipeline from right to left: the \verb'distance' function
takes the four arguments and returns a distance (the radius)
which is fed as an argument to the \verb'area'; with this
argument, \verb'area' is now able to return the area, which
is then returned by \verb'circle-area' to the caller code.
We'll come back later to this very expressive data pipeline
model.
\index{pipe-line programming}

\section{Boolean functions}
\label{boolean}

Functions can return Boolean values, which is often convenient for hiding
complicated tests inside functions. For example:
\index{Boolean function}

\begin{verbatim}
sub is-divisible(Int $x, Int $y) {
    if $x % $y == 0 {
        return True;
    } else {
        return False;
}
\end{verbatim}
%
It is common to give boolean functions names that sound like yes/no
questions; \verb"is-divisible", for instance, returns either
{\tt True} or {\tt False} to indicate whether {\tt x} is
divisible by {\tt y}.

Here is an example:

\begin{verbatim}
> is-divisible(6, 4);
False
> is-divisible(6, 3);
True
\end{verbatim}
%
The result of the {\tt ==} operator is a boolean value, so we
can write the subroutine more concisely by returning it directly:

\begin{verbatim}
sub is-divisible(Int $x, Int $y) {
    return $x % $y == 0
}
\end{verbatim}
%
If there is no return statement, a Perl subroutine returns the
value of expression on the last code line of the subroutine
(provided the last code line is an expression that gets evaluated), so that the
{\tt return} statement is not required here. In addition,
since 0 is a false value and any other integer a true value,
this could be further rewritten as follows:
\begin{verbatim}
sub is-divisible(Int $x, Int $y) {
    not $x % $y
}
\end{verbatim}

The {\tt Int} type declarations in the subroutine signatures above
are not necessary. The subroutine would work without them, but
they can provide some form of protection against using this
subroutine with faulty arguments.

Boolean functions are often used in statement modifiers:
\index{statement modifier}
\index{modifier!statement}

\begin{verbatim}
say "$x is divisible by $y" if is-divisible($x, $y);
\end{verbatim}
%
It might be tempting to write something like:

\begin{verbatim}
say "$x is divisible by $y" if is-divisible($x, $y) == True;
\end{verbatim}
%
But the extra comparison is unnecessary: {\tt is-divisible}
returns a boolean value that can be interpreted directly by
the {\tt if} conditional.

\label{isbetween}
As an exercise, write a function \verb"is-between(x, y, z)" that
returns {\tt True} if $x \le y \le z$ or {\tt False} otherwise.
Solution: \ref{sol_isbetween}.

\section{A complete programming language}

We've seen in the section above several ways of writing a
subroutine to check the divisibility of two integers.
\index{divisibility}

In fact, Perl~6 has a ``is divisible'' operator, \verb'%%', which returns {\tt True} if the number on the left is divisible by the one on the right:
%\index{%%!is divisible operator}
\index{is divisible operator}

\begin{verbatim}
> 9 %% 3
True
> 9 %% 4
False
\end{verbatim}

So there was no need to write the {\tt is-divisible} subroutine.
But don't worry, that's alright if you did not know that.
Speakers of natural languages are allowed to have different
skill levels, to learn as they go and to put the language
to good use before they know the whole language. The same
is true with Perl. You (and I) don't know all about Perl~6
yet, just as we don't know all of English. But it is in fact
``Officially Okay in Perl Culture'' to use the subset of
the language that you know. You are in fact
encouraged to use what is sometimes called ``baby Perl'' and
to write programs, even if they are somewhat clumsy at the
beginning. That's the best way of learning Perl, just as using
``baby talk'' is the right way for a child to learn English.
\index{baby Perl}
\index{Perl culture}

The number of different ways of accomplishing a given task,
such as checking whether one number is divisible
by another, is an example of one of Perl's mottos:
\emph{there is more than
one way to do it}, oft abbreviated TIMTOWTDI. Some ways may be
more concise or more efficient than others, but, in the Perl
philosophy, you are perfectly entitled to do it your way,
especially if you're a beginner, provided you find the correct
result.
\index{there is more than one way to do it}
\index{TIMTOWTDI}
\index{Turing!complete language}
\index{language!Turing complete}
\index{Turing, Alan}
\index{Turing!thesis}

We have only covered a small subset of Perl~6 so far, but you
might be interested to know that this subset is a {\em complete}
programming language, which means that essentially anything
that can be computed can be expressed in this language.
Any program ever written could be rewritten using only the
language features you have learned so far (actually, you
would need a few commands to control devices like the mouse,
disks, networks, etc., but that's all).

Proving that claim is a nontrivial exercise first accomplished by Alan
Turing, one of the first computer scientists (some would argue that he
was a mathematician, but a lot of early computer scientists started as
mathematicians).  Accordingly, it is known as the Turing Thesis.
For a more complete (and accurate) discussion of the Turing Thesis,
I recommend Michael Sipser's book {\em Introduction to the
Theory of Computation}.

\section{More recursion}
\label{more.recursion}
\index{recursion}

To give you an idea of what you can do with the tools you have learned
so far, we'll evaluate a few recursively defined mathematical
functions.  A recursive definition is similar to a circular
definition, in the sense that the definition contains a reference to
the thing being defined.  A truly circular definition is not very
useful:

\begin{description}

\item[vorpal:] An adjective used to describe something that is vorpal.
\index{vorpal}
\index{circular definition}
\index{definition!circular}

\end{description}

If you saw that definition in the dictionary, you might be annoyed. On
the other hand, if you looked up the definition of the factorial
function, denoted with the symbol $!$, you might get something like
this:
%
\begin{eqnarray*}
&&  0! = 1 \\
&&  n! = n (n-1)!
\end{eqnarray*}
%
This definition says that the factorial of 0 is 1, and the
factorial of any other (positive integer) value, $n$, is
$n$ multiplied by the factorial of $n-1$.

So $3!$ is 3 times $2!$, which is 2 times $1!$, which is 1 times
$0!$. Putting it all together, $3!$ equals 3 times 2 times 1 times 1,
which is 6.
\index{factorial!function}
\index{function!factorial}
\index{recursive definition}

If you can write a recursive definition of something, you can
write a Perl program to evaluate it. The first step is to decide
what the parameters should be.  In this case it should be clear
that {\tt factorial} takes a number\footnote{It should really be an
integer, but we'll get back to that later in this chapter.}:

\begin{verbatim}
sub factorial($n){
}
\end{verbatim}
%
If the argument happens to be 0, all we have to do is return 1:

\begin{verbatim}
sub factorial($n){
    if $n == 0 {
        return 1;
    }
}
\end{verbatim}
%
Otherwise, and this is the interesting part, we have to make a
recursive call to find the factorial of $n-1$ and then
multiply it by $n$:
\index{factorial!using recursion}

\begin{verbatim}
sub factorial($n){
    if $n == 0 {
        return 1;
    } else {
        my $recurse = factorial($n-1);
        my $result = $n * $recurse;
        return $result;
    }
}
\end{verbatim}
%
The flow of execution for this program is similar to the flow of {\tt
countdown} in Section~\ref{recursion}.  If we call {\tt factorial}
with the value 3:

Since 3 is not 0, we take the second branch and calculate the factorial
of {\tt \$n-1}...

\begin{quote}
Since 2 is not 0, we take the second branch and calculate the factorial of
{\tt \$n-1}...

  \begin{quote}
  Since 1 is not 0, we take the second branch and calculate the factorial
  of {\tt \$n-1}...

    \begin{quote}
    Since 0 equals 0, we take the first branch and return 1
    without making any more recursive calls.
    \end{quote}

  The return value, 1, is multiplied by \verb'$n', which is 1, and the
  result is returned.
  \end{quote}

The return value, 1, is multiplied by \verb'$n', which is 2, and the
result is returned.
\end{quote}

The return value (2) is multiplied by \verb'$n', which is 3, and
the result, 6, becomes the return value of the subroutine call
that started the whole process.
\index{stack diagram}

Figure~\ref{fig.stack3} shows what the stack diagram looks like for
this sequence of function calls.

\begin{figure}
\centerline
{\includegraphics[scale=0.8]{figs/stack3.pdf}}
\caption{Stack diagram.}
\label{fig.stack3}
\end{figure}

The return values are shown being passed back up the stack.  In each
frame, the return value is the value of {\tt result}, which is the
product of {\tt n} and {\tt recurse}.
\index{function!frame}
\index{frame}

In the last frame, the local
variables {\tt recurse} and {\tt result} do not exist, because
the branch that creates them does not run.

A seasoned Perl programmer might write a more concise or
more idiomatic subroutine\footnote{We will see later even
more idiomatic ways of computing the factorial of a number.}:
\index{idiomatic}

\begin{verbatim}
sub factorial($n){
    return 1 if $n == 0;
    return $n * factorial $n-1;
}
\end{verbatim}
%
This is not better than our initial version, and will probably
not run significantly faster, but this is arguably clearer,
at least once you get used to this type of syntax.

\section{Leap of faith}
\index{recursion}
\index{leap of faith}

Following the flow of execution is one way to read programs, but
it can quickly become overwhelming.  An alternative is what may
be called the ``leap of faith''.  When you come to a
subroutine call, instead of following the flow of execution, you {\em
assume} that the subroutine works correctly and returns the right
result.

In fact, you are already practicing this leap of faith when you use
built-in functions.  When you call math functions such as {\tt cos} or {\tt sqrt},
you don't examine the bodies of those functions.  You just
assume that they work because the people who wrote the built-in
functions were good programmers (and because you can safely
assume that they have been thoroughly tested).

The same is true when you call one of your own subroutines.  For
example, in Section~\ref{boolean}, we wrote a subroutine called
\verb"is-divisible" that determines whether one number is divisible by
another.  Once we have convinced ourselves that this subroutine is
correct---by examining the code and testing---we can use the subroutine without looking at the body again.
\index{testing!leap of faith}

The same is true of recursive programs.  When you get to the recursive
call, instead of following the flow of execution, you should assume
that the recursive call works (returns the correct result) and then ask
yourself, ``Assuming that I can find the factorial of \verb"$n-1", can I
compute the factorial of \verb"$n"?''  It is clear that you
can, by multiplying by \verb"$n".

Of course, it's a bit strange to assume that the subroutine works
correctly when you haven't finished writing it, but that's why
it's called a leap of faith!

\section{One more example}
\label{one.more.example}

\index{Fibonacci!function}
\index{function!Fibonacci}
After {\tt factorial}, the most common example of a recursively
defined mathematical function is {\tt fibonacci}, which has the
following definition (see
  \url{http://en.wikipedia.org/wiki/Fibonacci_number}):
%
\begin{eqnarray*}
&& \mathrm{fibonacci}(0) = 1 \\
&& \mathrm{fibonacci}(1) = 1 \\
&& \mathrm{fibonacci}(n) = \mathrm{fibonacci}(n-1) + \mathrm{fibonacci}(n-2)
\end{eqnarray*}
%

In plain English, a Fibonacci sequence is a sequence of numbers
such as:
\begin{verbatim}
1, 1, 2, 3, 5, 8, 13, 21, ...
\end{verbatim}
where the two first terms are equal to 1 and any other term is the
sum of the two preceding ones.

Translated into Perl, it looks like this:

\begin{verbatim}
sub fibonacci ($n) {
    return 1 if $n == 0 or $n == 1;
    return fibonacci($n-1) + fibonacci($n-2)
\end{verbatim}
%
If you try to follow the flow of execution here, even for fairly
small values of \verb'$n', your head explodes.  But according to the
leap of faith, if you assume that the two recursive calls
work correctly, then it is clear that you get
the right result by adding them together.
\index{flow of execution}

\section{Checking types}
\label{guardian}

What happens if we call {\tt factorial} and give it 1.5 as an argument?
\index{type!checking}
\index{error checking}
\index{factorial!function}

It seems that we get an infinite recursion.  How can that be?
The subroutine has a base case---when {\tt \$n == 0}.  But if {\tt \$n}
is not an integer, we can {\em miss} the base case and recurse forever.
\index{infinite recursion}
\index{recursion!infinite}
\index{base case}

In the first recursive call, the value of {\tt \$n} is 0.5.
In the next, it is -0.5.  From there, it gets smaller
(more negative), but it will never be 0.

We have two choices.  We can try to generalize the {\tt factorial}
function to work with non-integer numbers, or we can make {\tt
factorial} check its argument.  The first option is
called the gamma function and it's a
little beyond the scope of this book.  So we'll go for the second.
\index{function!gamma}
\index{gamma function}

We have already seen examples of subroutines using the signature
to verify the type of the argument. So we can add the {\tt Int}
type to the parameter in the signature. While we're at it,
we can also make sure the argument is positive or zero.

\begin{verbatim}
sub factorial(Int $n where $n >= 0){
    return 1 if $n == 0;
    return $n * factorial $n-1;
}
\end{verbatim}
%
\index{constraint}
\index{trait}
The {\tt Int} type checking in the signature handles
non-integers, this is not new. The {\tt where \$n >= 0}
part is a parameter constraint: if the parameter is negative,
the subroutine should fail.  Technically, the constraint is
implemented here within the signature using a syntax feature
called a \emph{trait}, that is a property imposed on the
parameter at compile-time. If the argument passed to the
function is not an integer or if it is negative, the program prints
an error message to indicate that something went wrong:

\begin{verbatim}
> say factorial 1.5
Type check failed in binding $n; expected Int but got Rat
  in sub factorial at <unknown file> line 1
  in block <unit> at <unknown file> line 1

> say factorial -3
Constraint type check failed for parameter '$n'
> say factorial "Fred"
Type check failed in binding $n; expected Int but got Str
  in sub factorial at <unknown file> line 1
  in block <unit> at <unknown file> line 1
\end{verbatim}
%
If we get past both checks, we know that \verb'$n' is an
integer and that it is positive or zero, so we can prove
that the recursion terminates.

\index{subset!type}
\index{type subset}
Another way to achieve a similar result is to define your own
subset of the built-in types. For example, you can create an
{\tt Even-int} subset of integers and then use it more or less
as if it were a new type for declaring your variables or
typing your subroutine parameters:

\begin{verbatim}
subset Even-int of Int where { $_ %% 2 } # or : … where { $_ % 2 == 0 }
# Even-int can now be used as a type

my Even-int $x = 2; # OK
my Even-int $y = 3; # Type mismatch error
\end{verbatim}

Similarly, in the case of the {\tt factorial} subroutine, we
can create a \emph{non-negative integer} subset and use it
for checking the parameter passed to the subroutine:

\begin{verbatim}
subset Non-neg-int of Int where { $_ >= 0}
# ...

sub factorial(Non-neg-int $n){
    return 1 if $n == 0;
    return $n * factorial $n-1;
}
\end{verbatim}
%
If we pass a negative integer to the subroutine, we get
a similar error as before:

\begin{verbatim}
Constraint type check failed for parameter '$n'...
\end{verbatim}

\index{guardian pattern}
\index{pattern!guardian}
This program demonstrates a pattern sometimes called a {\bf guardian}.
The signature acts as guardian, protecting the code that
follows from values that might cause an error.  The guardians make it
possible to prove the correctness of the code.

\section{Multi subroutines}
\label{multisubs}
\index{multi!subroutine}

It is possible to write multiple versions of a subroutine
with the same name but with different signatures, for example
a different \emph{arity} (a fancy word for the number of
arguments) or different argument types, using the
{\tt multi} keyword. In this case, the interpreter will
pick the version of the subroutine whose signature
matches (or best matches) the argument list.
\index{arity}

For example, we could rewrite the factorial function
as follows:
\index{factorial!using multi subroutines}

\begin{verbatim}
multi sub fact(0) { 1 };
multi sub fact(Int $n where $n > 0) {
    $n * fact $n - 1;
}
say fact 0;   # -> 1
say fact 10;  # -> 3628800
\end{verbatim}

Here, we don't enter into infinite recursion because, when
the parameter passed to {\tt fact} is 0, it is the first
version of the multi subroutine that is called and it returns
an integer value (1), and this ends the recursion.

Similarly, the Fibonacci function can be rewritten with
multi subroutines:
\index{Fibonacci!function with multi subroutines}

\begin{verbatim}
multi fibonacci(0) { 0 }
multi fibonacci(1) { 1 }
multi fibonacci(Int $n where $n > 1) {
    fibonacci($n - 2) + fibonacci($n - 1)
}
say fibonacci 10;  # -> 55
\end{verbatim}

Many built-in functions and most operators of Perl~6 are
written as multi subroutines.

\section{Debugging}
\label{factdebug}

Breaking a large program into smaller functions or subroutines
creates natural checkpoints for debugging.  If a subroutine
is not working, there are three possibilities to consider:
\index{debugging}

\begin{itemize}

\item There is something wrong with the arguments the subroutine
is getting; a precondition is violated.

\item There is something wrong with the subroutine; a post-condition
is violated.

\item There is something wrong with the return value or the
way it is being used.

\end{itemize}

To rule out the first possibility, you can add a {\tt print} statement
at the beginning of the function and display the values of the
parameters (and maybe their types).  Or you can write code
that checks the preconditions explicitly.
\index{precondition}
\index{postcondition}

For the purpose of debugging, it is often useful to print the content of a variable or of a parameter within a string with surrounding characters, so that you may visualize characters that are otherwise invisible, such as spaces or newline. For example, you think that the \verb'$var' should contain ``two'', but the test:
\begin{verbatim}
if $var eq "two" {
    do-something()
}
\end{verbatim}
%
fails and the {\tt do-something} subroutine is never called.

Perhaps you want to use a print statement that will ascertain
the content of \verb'$var':
\begin{verbatim}
say "[$var]";
if $var eq "two" {
    do-something()
}
\end{verbatim}
%

This might print:
\begin{verbatim}
[two ]
\end{verbatim}
%

or:
\begin{verbatim}
[two
]
\end{verbatim}
%
Now, you know that the equality test fails because \verb'$var'
contains a trailing character (space or newline) that might otherwise
be difficult to detect.

If the parameters look good, add a {\tt print} statement before each
{\tt return} statement and display the return value.  If
possible, check the result by hand.  Consider calling the
function with values that make it easy to check the result
(as in Section~\ref{incremental.development}).

If the function seems to be working, look at the function call
to make sure the return value is being used correctly (or used
at all!).
\index{flow of execution}

Adding print statements at the beginning and end of a function
can help make the flow of execution more visible.
For example, here is a version of {\tt factorial} with
print statements:
\index{factorial!recursive function with debug statements}

\begin{verbatim}
sub factorial(Int $n) {
    my $space = ' ' x (4 * $n);
    say $space, 'factorial ', $n;
    if $n == 0 {
        say $space, 'returning 1';
        return 1;
    } else {
        my $result = $n * factorial $n-1;
        say $space, 'returning ', $result;
        return $result;
    }
}
\end{verbatim}
%
The {\tt \$space} variable is a string of space characters that controls the
indentation of the output.  Here is the result of {\tt factorial(4)} :

\begin{verbatim}
                factorial 4
            factorial 3
        factorial 2
    factorial 1
factorial 0
returning 1
    returning 1
        returning 2
            returning 6
                returning 24
\end{verbatim}
%
If you are confused about the flow of execution, this kind of
output can be helpful.  It takes some time to develop effective
scaffolding, but a bit of scaffolding can save a lot of debugging.

\section{Glossary}

\begin{description}

\item[temporary variable:]  A variable used to store an intermediate value in
a complex calculation.
\index{temporary variable}
\index{variable!temporary}

\item[dead code:]  Part of a program that can never run, often because
it appears after a {\tt return} statement.
\index{dead code}

\item[incremental development:]  A program development plan intended to
avoid debugging by adding and testing only
a small amount of code at a time.
\index{incremental development}

\item[scaffolding:]  Code that is used during program development but is
not part of the final version.
\index{scaffolding}

\item[guardian:]  A programming pattern that uses a conditional
statement to check for and handle circumstances that
might cause an error.
\index{guardian pattern}
\index{pattern!guardian}

\end{description}

\section{Exercises}

\begin{exercise}

Draw a stack diagram for the following program.  What does
the program print? Please try to answer these questions before
trying to run the program.
\index{stack diagram}

\begin{verbatim}[fontshape=up]
sub b(Int $z) {
    my $prod = a($z, $z);
    say $z, " ", $prod;
    return $prod;
}
sub a(Int $x is copy, Int $y) {
    $x++;
    return $x * $y;
}
sub c(Int $x, Int $y, Int $z) {
    my $total = $x + $y + $z;
    my $square = b($total) ** 2;
    return $square;
}

my $x = 1;
my $y = $x + 1;
say c($x, $y + 3, $x + $y);
\end{verbatim}

\end{exercise}

\begin{exercise}
\label{ackermann}
\index{Ackermann function}

The Ackermann function, $A(m, n)$, is defined:

\begin{eqnarray*}
A(m, n) = \begin{cases}
              n+1 & \mbox{if } m = 0 \\
        A(m-1, 1) & \mbox{if } m > 0 \mbox{ and } n = 0 \\
A(m-1, A(m, n-1)) & \mbox{if } m > 0 \mbox{ and } n > 0.
\end{cases}
\end{eqnarray*}
%
See \url{http://en.wikipedia.org/wiki/Ackermann_function}.
Write a subroutine named {\tt ack} that evaluates the Ackermann function.
Use your subroutine to evaluate {\tt ack(3, 4)}, which should be 125.
What happens for larger values of {\tt m} and {\tt n}?
Solution: \ref{sol_ackermann}.
\index{Ackermann function}
\index{function!ack}

\end{exercise}

\begin{exercise}
\label{palindrome}
\index{palindrome}

A palindrome is a word that is spelled the same backward and
forward, like ``noon'' and ``redivider''.  Recursively, a word
is a palindrome if the first and last letters are the same
and the middle is a palindrome.
\index{palindrome}

The following are subroutines that take a string argument and
return the first, last, and middle letters:

\begin{verbatim}[fontshape=up]
sub first_l(Str $word){
    return substr $word, 0, 1;
}

sub last_l(Str $word){
    return substr $word, *-1, 1;
}

sub middle_l(Str $word){
    return substr $word, 1, *-1;
}
\end{verbatim}
%
We'll see how they work in Chapter~\ref{strings} on strings.
For now:

\begin{enumerate}

\item Type these subroutines into a file named {\tt palindrome.pl6}
and test them out.  What happens if you call {\tt middle} with
a string with two letters?  One letter?  What about the empty
string, which is written \verb"''" and contains no letters?
Given that the {\tt .chars} method returns the length of a
string, how could you add a signature constraint to reject invalid input?

\item Write a subroutine called \verb"is-palindrome" that takes
a string argument and returns {\tt True} if it is a palindrome
and {\tt False} otherwise.  Remember that you can use the
built-in method {\tt .chars} to check the length of a string.

\end{enumerate}

Solution: \ref{sol_palindrome}.
\index{palindrome}

\end{exercise}

\begin{exercise}
\index{power}
\label{power}

An integer number, $a$, is a power of $b$ if it is divisible by $b$
and $a/b$ is a power of $b$.  Write a function called
\verb"is-power-of" that takes parameters {\tt a} and {\tt b}
and returns {\tt True} if {\tt a} is a power of {\tt b}.
Note: you will have to think about the base case.
\index{base case}

Solution: \ref{sol_power}

\end{exercise}

\begin{exercise}
\index{greatest common divisor (GCD)}
\index{GCD (greatest common divisor)}
\label{gcd}
\index{gcd}

The greatest common divisor (GCD) of $a$ and $b$ is the largest number
that divides both of them with no remainder.

One way to find the GCD of two numbers is based on the observation
that if $r$ is the remainder when $a$ is divided by $b$, then $gcd(a,
b) = gcd(b, r)$.  As a base case, we can use $gcd(a, 0) = a$.

Write a function called
\verb"gcd" that takes parameters {\tt a} and {\tt b}
and returns their greatest common divisor.

Credit: This exercise is based on an example from Abelson and
Sussman's {\em Structure and Interpretation of Computer Programs}.
\index{Abelson, Harold}
\index{Sussman, Gerald Jay}

Solution: \ref{sol_gcd}

\end{exercise}


% !TeX program = lualatex -synctex=1 -interaction=nonstopmode --shell-escape %.tex

\documentclass[international_finance_p1.tex]{subfiles}

\begin{document}
\setbeamercovered{transparent}
\section{Forward-looking Market Instruments}

\subsection{The currency forwards}
\begin{frame}{The currency forwards}
\begin{block}{The currency forward }
   is a contract in the foreign exchange market that locks in the exchange rate for the purchase or sale of a currency on a future date.
\end{block}
\begin{itemize}[<+->]
\item
A currency forward represents \emph{a binding obligation}, which means that the contract buyer or seller cannot walk away if the ``locked in'' rate eventually proves to be adverse.
\item
To compensate for the risk of non-delivery, financial institutions may require a \emph{deposit }from retail investors or smaller firms with whom they do not have a business relationship.
\end{itemize}
\end{frame}
\begin{frame}{Determining a currency forward rate}
\begin{align}
F=\frac{\text{Bid}+\text{Ask}}{2}\cdot \frac{1+i_1 \cdot \frac{n}{365}}{1+i_2 \cdot \frac{n}{365}}
\end{align}

where

$F$ – forward rate;

Bid, Ask – spot bid and ask rate respectively;

$i_1$ – annual interest rate for quoted currency;

$i_2$ – annual interest rate for base currency;

$n$ – forward contract period in days
\end{frame}
\setbeamercovered{invisible}
\begin{frame}
\begin{exampleblock}{Forward rate calculation}
assume a current spot rate for the Russian ruble of US\$1 = RUR76.45 or USD/RUR=76.45, a one-year interest rate for Russian rubles of 8\% (key rate held by the Central Bank of Russian Federation), and one-year interest rate for US dollars of 0.25\%. Assume that USD/RUR bid and ask are 75.00 and 76.0 respectively. So, 3-months (3M) forward interest rate would be
\begin{align*}
F_{3M;USDRUB}&=\onslide<2->{ \frac{75+76}{2} \cdot \frac{1+0.08 \cdot \frac{90}{365}}{1+0.0025 \cdot \frac{90}{365}}\\}
\onslide<3->{F_{3M;USDRUB}&=76,9419}
\end{align*}
\end{exampleblock}
\end{frame}
\setbeamercovered{transparent}
\subsection{The foreign exchange swaps}
\begin{frame}
\begin{block}{A foreign exchange swap }
\quad is an arrangement where there is a simultaneous exchange of two currencies on a specific date at a rate agreed at the time of the contract, and a reverse exchange of the same two currencies at a date further in the future at a rate agreed at the time of the contract.
\end{block}
A foreign exchange swap consists of two legs:

1) a spot foreign exchange transaction, and;

2) a forward foreign exchange transaction.
\end{frame}
\begin{frame}{The forward points or swap points }
are quoted as the difference between forward and spot: $F - S$.
\begin{align}
F-S&=S \left(\frac{1+i_1 \cdot \frac{n}{base}}{1+i_2 \cdot \frac{n}{base}}-1\right)\nonumber\\
&=\frac{S(i_1-i_2)T}{1+i_2T}\nonumber\\
&\approx S(i_1-i_2)T
\end{align}
where
$n$ - forward contract term;

$T=\frac{n}{base}$;

$base=\text{365 or 366}$.
If $i_2T$ is small. Thus, the value of the swap points is roughly proportional to the interest rate differential.

The most common use of foreign exchange swaps is for institutions to fund their foreign exchange balances
\end{frame}
\setbeamercovered{invisible}
\begin{frame}
\begin{exampleblock}{Swap points calculation}
% Table generated by Excel2LaTeX from sheet 'Лист2'
\begin{table}[htbp]
  \centering
  \caption{Assume that we have such\\RUB and USD interest rates}
    \begin{tabular}{lr}
    \toprule
    \%RUB & 8\% \\
    \midrule
    \%USD & 0,25\% \\
    n     & 90 \\
    base  & 365 \\
    $SW_{USDRUB}$ & \onslide<2->{0,01911} \\
    \bottomrule
    \end{tabular}%
  \label{tab:addlabel}%
\end{table}%
\end{exampleblock}
\end{frame}
\setbeamercovered{transparent}
\subsection{The currency swaps}
\begin{frame}{}
\begin{itemize}[<+->]
\item
A currency swap is a contract in which two counterparties exchange streams of interest payments in different currencies for an agreed period of time and then exchange principal amounts in the respective currencies at an agreed exchange rate at maturity.
\item
Currency swaps allow firms to obtain long-term foreign currency financing at lower cost than they can by borrowing directly
\end{itemize}
\end{frame}
\begin{frame}{}
% Table generated by Excel2LaTeX from sheet 'Лист3'
\begin{table}[htbp]
  \centering
  \caption{Loan rates for two firms in different currencies}
    \begin{tabular}{lrr}
    \toprule
          & USD interest rate, \% & EUR interest rate, \% \\
    \midrule
    Firm A & 10    & 7 \\
    Firm B & 9     & 8 \\
    \bottomrule
    \end{tabular}%
  \label{tab:addlabel}%
\end{table}%
Suppose, US firm has free access to loans from US banks, but can not have such favorable opportunities on Germany capital market.

Similarly, the German firm can have good loan conditions in the homeland, but far less favorable ones in the USA.

By currency swap agreement both firms can use comparative advantages of each other to reduce the cost of loan.

\end{frame}

\begin{frame}[shrink=10]{Cash flows of the two borrowers}{in currency swap agreement}
\begin{figure}
	\centering
	\begin{overprint}
		\forloop{slideno}{1}{\value{slideno} < 2}{%
			\only<\value{slideno}>{
				\includegraphics[page=\value{slideno},
				scale=.7
				% trim={<left> <lower> <right> <upper>}
				,trim={0cm 1cm 1.5cm 0cm},clip]
				{tikz/currency_swap}}}
	\end{overprint}
	\vspace*{-1.5em}
	\caption{\captionf{Currency swap}}
\end{figure}
\end{frame}

\begin{frame}
Thus, both firms obtain the loans in necessary foreign currency at a lower rate, than it would be in case of the request for the credit directly in foreign bank. As a whole the Firm A saves on interest payments 0,8 ml – 0,7 ml = 0,1 ml EUR, and the Firm B saves on interest payments 1,25 ml – 1,125 ml = 0,125 ml USD.
\end{frame}

\subsection{The foreign exchange futures}
\begin{frame}
Futures are similar to forward contracts. Each future contract has a fixed amount and pre-determined dates. The difference of futures from forwards consists in the following:

1. Futures trading is carried out on the open exchange market, and forwards – on interbank. Therefore dates of future contracts expiration are attached to certain dates. Futures contracts are standardized on expiration periods, volumes and terms of delivery. In case of forward contracts expiration periods and volumes of the transaction are determined by the mutual arrangement of the parties.

2. Futures are traded only on most liquid currency pairs. Forward contracts are traded almost on all currency pairs.
\end{frame}
\begin{frame}
3. The futures market is available not only to big investors, but also small. The forward market is limited by that the minimum sum for the transaction amounts 500 thousand US dollars.

4. For about 95\% futures trading volume come to an end with the conclusion of the opposite transaction, thus there is no real delivery of the currency. The parties receive only a difference between the initial price of the contract and the price existing in the day of the closing transaction. On the contrary, for about 95\% forwards transactions come to an end with currency delivery.

5. Futures transactions cost are cheaper because of standardization.

\end{frame}
\subsection{The foreign exchange options}
\begin{frame}
\begin{block}{Foreign currency options }
\quad are contracts that give a buyer the right to buy (call option) or sell (put option) currencies at a specified price within a specific period of time. The strike price is the price at which the owner of the contract has the right but not the obligation to transact.
\end{block}
\end{frame}
\begin{frame}{Comparison of currency call and put options I}
\begin{columns}
\begin{column}{0.5\textwidth}
\textbf{Currency call option}

1. In case the currency call option is executed, expenses of the currency buyer will make:
$$R_{oe}=R_o+P,$$

where $R_o$ – an exchange rate at which the currency will be acquired;

$P$ – premium for the option (buyer`s expenses).

\end{column}
\begin{column}{0.5\textwidth}  %%<--- here
\textbf{Currency put option}

1. In case the currency put option is executed, revenue of the currency seller will make:
$$R_{oe}=R_o-P,$$

where $R_o$ – an exchange rate at which the currency will be acquired;

$P$ – premium for the option (seller`s expenses anyway).
\end{column}
\end{columns}
\end{frame}

\begin{frame}{Comparison of currency call and put options II}
\begin{columns}
\begin{column}{0.5\textwidth}
\textbf{Currency call option}

2. In case the currency call option isn't executed, expenses of the currency buyer will make:
$$R_{te}=R_t+P,$$

where $R_t$ – the current market currency rate of exchange.
\end{column}
\begin{column}{0.5\textwidth}  %%<--- here
\textbf{Currency put option}

2. In case the currency put option isn't executed, revenue of the currency seller will make:
$$R_{te}=R_t-P,$$

where $R_t$ – the current market currency rate of exchange.
\end{column}
\end{columns}
\end{frame}

\begin{frame}{Comparison of currency call and put options III}
\begin{columns}
\begin{column}{0.5\textwidth}
\textbf{Currency call option}

3. As the buyer is interested in minimization of the expenses, a condition under which execution of this option will be favorable to him, will be:
\begin{align*}
 R_{oe} &< R_{te}\\
 &or \\
 R_o &< R_t.
\end{align*}
\end{column}
\begin{column}{0.5\textwidth}  %%<--- here
\textbf{Currency put option}

3. As the seller is interested in maximization of the revenue, a condition under which execution of this option will be favorable to him, will be:
\begin{align*}
 R_{oe} &> R_{te}\\
 &or \\
 R_o &> R_t.
\end{align*}
\end{column}
\end{columns}
\end{frame}

\begin{frame}{Comparison of currency call and put options IV}
\begin{columns}
\begin{column}{0.5\textwidth}
\textbf{Currency call option}

4. The buyer of the call option will make profit, if rate of exchange will rise so that it can cover option premium, i.e.
$$R_{oe} + P < R_{te}$$

If both sides of inequality are equal, the trade will be break-even.
\end{column}
\begin{column}{0.5\textwidth}  %%<--- here
\textbf{Currency put option}

4. The buyer of the put option will make profit, if rate of exchange will fall so that it can cover option premium, i.e.
$$R_{oe}-P>R_{te}$$

If both sides of inequality are equal, the trade will be break-even.
\end{column}
\end{columns}
\end{frame}

\begin{frame}[shrink=10]{}
\begin{exampleblock}{Example}
Consider the firm in Russia that needs \$1 million US dollars in 3 months. The firm decided to buy 3-months call option contract for USD/RUR
% Table generated by Excel2LaTeX from sheet 'optionprem'
\begin{table}[htbp]
  \centering
  \caption{Currency market conditions}
    \begin{tabular}{lrr}
    \toprule
          & Bid   & Ask \\
    \midrule
    USD/RUR spot rate & 32.5  & 33.2 \\
    USD/RUR 3-months forward premium & 0.6   & 0.8 \\
    USD/RUR 3-month option premium & 0.2   & 0.2 \\
    \bottomrule
    \end{tabular}%
  \label{tab:addlabel}%
\end{table}%
Should the firm execute the option if the Bid/Ask rate of exchange for USD/RUR makes, respectively, 32.80 and 33.40 in three months?
\end{exampleblock}
\end{frame}
\setbeamercovered{invisible}
\begin{frame}{}
\begin{exampleblock}{Solution}
If the firm execute the call option, its costs of dollar`s purchase will make

\onslide<2->
33,20 + 0,80 + 0,20 = 34,20.

\onslide<3->
If the firm doesn't execute the option, its expenses will make:

\onslide<4->
33,40 + 0,20 = 33,60.

\onslide<5->
Thus, option execution will be unprofitable to firm since increases its costs of dollar`s purchase per 0,60 rubles for one dollar.
\end{exampleblock}
\end{frame}
\setbeamercovered{transparent}
\subsection{Pricing forex options}

\end{document}


\subsection{Schedule and Readings}\label{sub:schedule}%{{{

\subsubsection{Week 1 (5/9-): Why visualization?} %{{{

\begin{itemize}\itemsep0em
\item J. Heer \emph{et al}. A Tour through the Visualization Zoo. \url{https://queue.acm.org/detail.cfm?id=1805128}
\item J. VanderPlas, The Python Visualization Landscape. \url{https://youtu.be/FytuB8nFHPQ}
\item Further readings: \url{https://github.com/yy/dviz-course/blob/master/m01-intro/class.md}
\end{itemize}

%}}}
\subsubsection{Week 2 (5/16-): History and integrity}%{{{

\begin{itemize}\itemsep0em
\item E.R. Tufte, The Visual Display of Quantitative Information, Ch.~1--2.
\item C.O. Wilke, Fundamentals of Data Visualization Ch.~1 (\url{https://serialmentor.com/dataviz/introduction.html}).
\item Further readings: \url{https://github.com/yy/dviz-course/blob/master/m02-history/class.md} and \url{https://github.com/yy/dviz-course/blob/master/m03-integrity/class.md}
\end{itemize}

%\subsubsection{Week 3 (5/20-): Labor day | Web, Declarative vs. Procedural visualization }

%}}}
\subsubsection{Week 3 (5/23-): Perception}%{{{

\begin{itemize}\itemsep0em
\item C.G. Healey, Perception in Visualization, \url{https://www.csc2.ncsu.edu/faculty/healey/PP/index.html}
\item B. Wong, Color Coding, Nature Methods (2010).
\item B. Wong, Avoiding color, Nature Methods (2011).
\item C.O. Wilke, Fundamentals of Data Visualization Ch.~4 Color scales (\url{https://serialmentor.com/dataviz/color-basics.html}).
\item C.O. Wilke, Fundamentals of Data Visualization Ch.~15 Common pitfalls of color use (\url{https://serialmentor.com/dataviz/color-pitfalls.html}).
\item Further readings: \url{https://github.com/yy/dviz-course/blob/master/m04-perception/class.md}
\end{itemize}
%}}}
\subsubsection{Week 4 (5/30-): Design }%{{{

\begin{itemize}\itemsep0em
\item B. Wong, Gestalt Principles I \& II, Nature Methods (2010).
\item E.R. Tufte, The Visual Display of Quantitative Information, Ch.~4.
\item S. Bateman et al., Useful Junk? The Effects of Visual Embellishment on Comprehension and Memorability of Charts, CHI'10.
\item C.O. Wilke, Fundamentals of Data Visualization Ch.~18--21 (\url{https://serialmentor.com/dataviz/optimize-data-signal.html}).
\item Further readings: \url{https://github.com/yy/dviz-course/blob/master/m05-design/class.md}
\end{itemize}
%}}}
\subsubsection{Week 5 (6/6-): Data Types and 1-D data } %{{{

\begin{itemize}\itemsep0em
\item H. Wickham, Tidy Data, Journal of Statistical Software, \url{https://vita.had.co.nz/papers/tidy-data.pdf}
\item C.O. Wilke, Fundamentals of Data Visualization Ch.~14 (\url{https://serialmentor.com/dataviz/overlapping-points.html}).
\item Further readings: \url{https://github.com/yy/dviz-course/blob/master/m06-data/class.md}
\end{itemize}
%}}}
\subsubsection{Week 6 (6/13-): Histogram and Boxplot }%{{{

\begin{itemize}\itemsep0em
\item C.O. Wilke, Fundamentals of Data Visualization Ch.~6--7 (\url{https://serialmentor.com/dataviz/overlapping-points.html}).
\item Further readings: \url{https://github.com/yy/dviz-course/blob/master/m07-1D/class.md} and \url{https://github.com/yy/dviz-course/blob/master/m08-histogram/class.md}
\end{itemize}
%}}}
\subsubsection{Week 7 (6/20-): Estimation and logscale }%{{{

\begin{itemize}\itemsep0em
\item C.O. Wilke, Fundamentals of Data Visualization Ch.~8--9 (\url{https://serialmentor.com/dataviz/overlapping-points.html}).
\item Further readings: \url{https://github.com/yy/dviz-course/blob/master/m09-estimation/class.md}
\item Khan Academy: Logarithmic scale with Vi Hart (\url{https://www.khanacademy.org/math/algebra2/exponential-and-logarithmic-functions/logarithmic-scale}).
\end{itemize}
%}}}
\subsubsection{Week 8 (6/27-): High-dimensional data }%{{{

\begin{itemize}\itemsep0em
\item C.O. Wilke, Fundamentals of Data Visualization Ch.~11 (\url{https://serialmentor.com/dataviz/visualizing-associations.html}).
\item 3Blue1Brown, Eigenvectors and eigenvalues \url{https://www.youtube.com/watch?v=PFDu9oVAE-g}.
\item Victor Powell, PCA \url{http://setosa.io/ev/principal-component-analysis/}.
\item L. van der Maaten \& G. Hinton, Visualizing data using t-SNE, JMLR 2008 \url{http://www.jmlr.org/papers/volume9/vandermaaten08a/vandermaaten08a.pdf}.
\item Further readings: \url{https://github.com/yy/dviz-course/blob/master/m10-logscale/class.md} and \url{https://github.com/yy/dviz-course/blob/master/m11-highdim/class.md}
\end{itemize}
%}}}
%\subsubsection{Week 9 (7/6-): High-dimensional data }%{{{

%\begin{itemize}\itemsep0em
%\item C.O. Wilke, Fundamentals of Data Visualization Ch.~11 (\url{https://serialmentor.com/dataviz/visualizing-associations.html}).
%\item 3Blue1Brown, Eigenvectors and eigenvalues \url{https://www.youtube.com/watch?v=PFDu9oVAE-g}.
%\item Victor Powell, PCA \url{http://setosa.io/ev/principal-component-analysis/}.
%\item L. van der Maaten \& G. Hinton, Visualizing data using t-SNE, JMLR 2008 \url{http://www.jmlr.org/papers/volume9/vandermaaten08a/vandermaaten08a.pdf}.
%\end{itemize}

%\subsubsection{Week 10 (7/8-): Mid-term}
%}}}
\subsubsection{Week 9 (7/4-): Maps }%{{{

\begin{itemize}\itemsep0em
\item Vsauce, What does earth look like? \url{https://youtu.be/2lR7s1Y6Zig}
\item Vox, Why all world maps are wrong \url{https://youtu.be/kIID5FDi2JQ}
\item Further readings: \url{https://github.com/yy/dviz-course/blob/master/m12-maps/class.md}
\end{itemize}
%}}}
\subsubsection{Week 10 (7/11-): Text and Networks } %{{{

\begin{itemize}\itemsep0em
\item J. Harris, Word clouds considered harmful, \url{http://www.niemanlab.org/2011/10/word-clouds-considered-harmful/}.
\item The Observatory of Economic Complexity, \url{https://atlas.media.mit.edu/en/profile/country/usa/}.
\item Further readings: \url{https://github.com/yy/dviz-course/blob/master/m13-text/class.md} and \url{https://github.com/yy/dviz-course/blob/master/m14-networks-and-interactive/class-network.md}
\end{itemize}
%\subsubsection{Week 14 (11/19-): Thanksgiving break}
%\subsubsection{Week 15 (11/26-): Project Hacks}
%}}}
\subsubsection{Week 11 (7/18-): Project week} %{{{
%}}}
%\subsubsection{Week 14 (11/25-): Thanksgiving break} %{{{
%}}}
%\subsubsection{Week 15 (12/2-): Project Hack week}%{{{
%}}}
\subsubsection{Week 12 (7/25-): Final exam week}%{{{
%}}}

%}}}

%}}}


\documentclass{article}

\usepackage{algorithm}
\usepackage{algorithmic}
\usepackage{graphicx}
\usepackage{marvosym}
\usepackage{dingbat}
\usepackage{tikz}

\title{Longest branch of a tree}
\date{}

\usetikzlibrary{arrows}

\tikzset{
  treenode/.style = {align=center, inner sep=0pt, text centered, font=\sffamily},
  wn/.style = {treenode, circle, black, font=\ttfamily, draw=white, fill=white, text width=1.5em},
  txt/.style = {black, anchor=west, font=\ttfamily, draw=white, fill=white},
  edge from parent/.style={thick,draw=black, latex-}
}

\begin{document}
\maketitle

\section{Longest tree branch}

This exercise is about parallelizing a Depth First Search (DFS) traversal of
a random tree. We assume that each node has a weight which corresponds
to the time it takes to process it. Our DFS traversal finds the
longest branch in the tree, i.e., the branch such that the sum of the
weigths of its nodes is maximum.

The tree is nodes of type \texttt{node\_t} which contain the following members

\begin{itemize}
\item \texttt{weight}: the weight of the node;
\item \texttt{branch\_weight}: the weight of the branch that connects
  the node to the root of the tree; this is set to zero at the
  beginning and is updated during the DFS traversal;
\item \texttt{id}: the node number;
\item \texttt{nc}: the number of children of the node.
\item \texttt{*children}: an array of pointers to the children of the node.
\end{itemize}

The traversal is done recursively using the following code

\begin{verbatim}
void longest_branch_seq_rec(node_t *root, unsigned int *weight, unsigned int *leaf){
  int i;
  process(root);
  root->branch_weight += root->weight;

  if(root->nc>0) {
    for(i=0; i<root->nc; i++){
      root->children[i].branch_weight = root->branch_weight;
      longest_branch_seq_rec(root->children+i, weight, leaf);
    }
  } else {
    if(root->branch_weight > *weight){
      *weight = root->branch_weight;
      *leaf   = root->id;
    }
  }
}
\end{verbatim}

The \texttt{weight} and \texttt{leaf} arguments of this function are
meant to return the weight of the longest branch and the corresponding
leaf.  When we visit a node, first we process it using the
\texttt{process} routine and we update the weight of the branch that
connects it to the root (i.e., we add its weight to the branch weight
of its father).  Then, if it has children, we recursively call this
code on each one of them, if not then it means that we have reached a
leaf of the tree; in this case if the weight of the current branch is
grater than the current maximum contained in the \texttt{weight}
variable, we update \texttt{weight} and \texttt{leaf}.

For example, on the tree below, this method would return the leaf
number $3$ and the associated weight of $137$.

\begin{center}
  \includegraphics[width=0.4\textwidth]{tree.pdf}
\end{center}

\section{Package content}
In the \texttt{tree\_branch} directory you will find the
following files:
\begin{itemize}
\item \texttt{main.c}: this file contains the main program which first
  initializes the tree for a provided number of maximum levels. The main
  program then calls a sequential routine \texttt{longest\_branch\_seq}
  containing the above code, then calls the
  \texttt{longest\_branch\_par} routine which is supposed to contain a
  parallel version of the traversal code.
\item \texttt{longest\_branch\_seq.c}: contains a routine implementing a
  sequential traversal with the code presented above.
\item \texttt{longest\_branch\_par.c} contains a routine implementing a
  parallel tree traversal. \textbf{Only this file has to be modified
    for this exercise}.
\item \texttt{aux.c, aux.h}: these two files contain auxiliary
  routines and \textbf{must not be modified}.
\end{itemize}

The code can be compiled with the \texttt{make} command: just type
\texttt{make} inside the \texttt{tree\_branch} directory; this
will generate a \texttt{main} program that can be run like this:

\begin{verbatim}
$ ./main l s
\end{verbatim}

where \texttt{l} is the number of levels in the tree. The argument $s$
is the seed for the random number generation (which is used to build
the tree), and can be used to create trees of different shapes for a
fixed number of levels.

\section{Assignment}
\begin{itemize}
\item {\huge \Keyboard} At the beginning, the
  \texttt{longest\_branch\_par} routine contains an exact copy of the
  \texttt{longest\_branch\_seq} one. Modify these routine in order to
  parallelize it.  Make sure that the result computed by the three
  routines (sequential and parallel ones) is consistently (that is, at
  every execution of the parallel code) the same; a message printed at
  the end of the execution will tell you whether this is the
  case. Note that there may be multiple branches of the same length;
  in this case any of them will be considered a correct result. Also,
  modify the code in order to count the number of nodes updated by
  each of the working threads.
\item \smallpencil Report the execution times for the implemented
  parallel version with 1, 2 and 4 threads and for different tree
  sizes. Analyze and comment on your results: is the achieved speedup
  reasonable or not? Report your answer in the \texttt{responses.txt}
  file.
\end{itemize}

\paragraph{Advice}
\begin{itemize}
\item As usual, when developing and debugging choose trees of small
  size. When evaluating performance it's better to choose a larges
  tree size.
\end{itemize}

\end{document}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% End:


\documentclass[12pt]{article}

\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{tabularx}
\usepackage{multicol}
\usepackage{algpseudocode}
\usepackage{algorithm}

% Geometry
\usepackage{geometry}
\geometry{letterpaper, left=15mm, top=20mm, right=15mm, bottom=20mm}

% Fancy Header
\usepackage{fancyhdr}
\renewcommand{\footrulewidth}{0.4pt}
\pagestyle{fancy}
\fancyhf{}
\chead{CSC 360 - Analysis of Algorithms}
\lfoot{CALU Fall 2021}
\rfoot{RDK}

% Add vertical spacing to tables
\renewcommand{\arraystretch}{1.4}

% Macros
\newcommand{\definition}[1]{\underline{\textbf{#1}}}

\newenvironment{rcases}
  {\left.\begin{aligned}}
  {\end{aligned}\right\rbrace}

% Begin Document
\begin{document}

\begin{itemize}

    \item Read Chapters 7 and 8 for Week 3. Quiz in Week 3.

    \item What governs how fast an algorithm can run?
    \begin{itemize}
        \item The complexity of the problem; a problem has a theoretical best solution
        \item The efficiency of the algorithm; an algorithm can give a close enough solution in a fraction of the time
    \end{itemize}

    \item Sometimes writing a program that always guesses the correct solution is not always good enough.
    \begin{itemize}
        \item Time complexity; a program taking too long for its answer; keep in mind timescales
    \end{itemize}

\end{itemize}

\section*{Properites of Exponents}

\begin{itemize}

    \item $x^a * x^b = x^{a+b}$
    \item $(x^a)^b = x^{ab}$
    \item $x^a / x^b = x^{a-b}$

\end{itemize}

\section*{Properties of Logarithms}
\begin{itemize}

    \item $x^a = b$ iff $log_x b = a$

    \item $log_a b = log_c b / log_c a$ if $a, b, c > 0, a \neq 0$
    \begin{itemize}
        \item Let $x = log_c b$, $y = log_c a$, $z = log_a b$
        \item $b = c^x, b=a^z \rightarrow b = c^x = a^z$
        \item $a = c^y$
        \item $b = c^x = c^{yz}$
        \item $x = yz \rightarrow z = x/y$
    \end{itemize}

    \item $logab = loga + logb$
    \begin{itemize}
        \item Let $x = log_2 a, y = log_2 b, z = log_2 ab$ if $a, b > 0$
        \item $2^x = a, 2^y = b, 2^z = ab$
        \item $2^x * 2^y = 2^z$
        \item $2^{x+y} = 2^z$
        \item $x + y = z$
    \end{itemize}

    \item $log_2 (a/b) = log_2 a - log_2 b$ if $a, b > 0$
    \begin{itemize}
        \item Let $x = log_2 a, y = log_2 b, z = log_2 (a/b)$
        \item $2^x = a, 2^y = b, 2^z = a / b$
        \item $2^x / 2^y = 2^z$
        \item $x-y = z$
    \end{itemize}

\end{itemize}

\pagebreak

\section*{Disproof}
\begin{itemize}
    \item Only need to find one counter example
    \item Example: $n! < n^2 + n^5$ \\
    \begin{tabular}{l l l}
        Pick $n=9$ & & \\
        $9! = 362880$ & $9^2 = 81$ & $9^5 = 59130$ \\
        $362880 < 81 + 59130$ & FALSE! &
    \end{tabular}
\end{itemize}

\section*{Proof by Induction}
\begin{itemize}
    \item Use proof by Induction for discrete types only.
    \item Happens in 3 steps:
    \begin{enumerate}
        \item Start with a (very small) base case.
        \item Inductive Hypothesis: ``Since we showed a base case in Step 1, let's assume it holds true for values through $k$''
        \item Show that if the Hypothesis works for value $k$, the Hypothesis holds for $k+1$
    \end{enumerate}
\end{itemize}

\subsection*{Example of Induction}

\[ \sum_{i=1}^{n} i = \frac{n(n+1)}{2} \]

\begin{enumerate}
    \item Let $n=1 \rightarrow 1 = 1$
    \item Assume the property is true for $1, 2, \ldots, k$
    \item Show if true for $k$, then true for $k+1$
    \\
    \begin{tabular}{l l l}
        $\sum_{i=1}^{k+1} i$ & $=$ & $\sum_{i=1}^{k} + k + 1$ \\
        & $=$ & $\frac{k(k+1)}{2} + k + 1$ \\
        & $=$ & $\frac{k(k+1)}{2} + \frac{2(k+1)}{2}$ \\
        & $=$ & $\frac{k(k+1) + 2(k+1)}{2}$ \\
        & $=$ & $\frac{(k+1)(k+2)}{2}$ \\
        & $=$ & $\frac{(k+1)(k+1+1)}{2}$ \\
    \end{tabular}

\end{enumerate}

\pagebreak

\subsection*{Example 2 of Induction}

\[ \sum_{i=1}^{n} i(i+1) = \frac{n(n+1)(n+2)}{3} \]

\begin{enumerate}
    \item Let $n=1 \rightarrow 2 = 2$
    \item Assume the property is true for $1, 2, \ldots, k$
    \item Show if true for $k$, then true for $k+1$
    \\
    \begin{tabular}{l l l}
        $\sum_{i=1}^{k+1} i(i+1)$ & $=$ & $\sum_{i=1}^{k} i(i+1) + (k+1)(k+2)$ \\
        & $=$ & $\frac{k(k+1)(k+2)}{3} + (k+1)(k+2)$ \\
        & $=$ & $\frac{k(k+1)(k+2)}{3} + \frac{3(k+1)(k+2)}{3}$ \\
        & $=$ & $\frac{k(k+1)(k+2) + 3(k+1)(k+2)}{3}$ \\
        & $=$ & $\frac{(k+1)(k+2)(k+3)}{3}$ \\
        & $=$ & $\frac{(k+1)(k+1+1)(k+1+2)}{3}$ \\
    \end{tabular}

\end{enumerate}

\subsection*{Example 3 of Induction}

Fibonnaci Numbers $\rightarrow F_0 = 1, F_1 = 1, \ldots, (F_i = F_{i-1} + F_{i-2})$

Prove that $F_i < ({\frac{5}{3}})^i$, for $i \geq 1$

\begin{enumerate}

    \item $F_1 = 1 < (\frac{5}{3})^1$
    \item Assume this is true for $1, \ldots, k$
    \item Show if true for $k$, then true for $k+1$
    \\
    \begin{tabular}{l l l l l}
        $F_{k+1}$ & $=$ & $F_k + F_{k-1}$ && \\
        $F_{k+1}$ & $<$ & $(\frac{5}{3})^k + (\frac{5}{3})^{k-1}$ && \\
        $F_{k+1}$ & $<$ & $(\frac{3}{5})(\frac{5}{3})^{k+1} + (\frac{3}{5})^2(\frac{5}{3})^{k+1}$ && \\
        $F_{k+1}$ & $<$ & $(\frac{5}{3})^{k+1} * ((\frac{3}{5})^2+(\frac{3}{5}))$ && \\
        $F_{k+1}$ & $<$ & $(\frac{5}{3})^{k+1} * (\frac{15}{25} + \frac{9}{25})$ && \\
        $F_{k+1}$ & $<$ & $(\frac{5}{3})^{k+1} * \frac{24}{25}$ & $<$ & $({\frac{5}{3}})^{k+1}$ \\
    \end{tabular}

\end{enumerate}

\end{document}


%!TEX root = ../main.tex
\section{Introduction}
\label{sec:introduction}
%Copatterns. This is an preparatory study for our master's thesis.
%How do we fit copatterns into Idris?
In the world of functional programming, the use of inductive data types has long been a standard practice. Inductive data types enable users to define fundamental data structures such as lists, trees, and graphs, and to analyze data by pattern matching. A fundamental property of inductively defined data is that it is inherently finite. Since it is defined in terms of constructors, infinite structures cannot be defined inductively in systems with finite memory unless certain evaluation strategies are abandoned. In particular, programming languages such as Haskell have successfully been able to blur the lines between finite and infinite structures through the power of lazy evaluation. An alternative approach is to define infinite data explicitly by the use of \emph{co}inductive data types. These were first implemented by Hagino for his SymML language\,\citep{Hagino89}, allowing users to define coinductive data in terms of its \emph{destructors}. This means that it does not make sense to think of coinductive data as something that is constructed. Rather, coinductive data can be thought of as something that can be taken apart and observed, and therefore the terms ``observation'' and ``destructor'' are used interchangably. Explicit coinductive data types have since been added to several other programming systems, examples of which are the Coq proof system\,\citep{Coq:manual}, Agda\,\citep{Norell:thesis}, Beluga\,\citep{Pientka10}, and Idris\,\citep{BradyIdrisImpl13}.

While most (if not all) systems with inductive data types have a pattern matching construct for analyzing data, many systems with coinductive data types do not have dedicated constructs for manipulating destructors. Instead, coinductive data is also subjected to pattern matching. In SymML, Hagino describes a \texttt{merge} construct for describing how a coinductive definition can be destructed, an example of which is shown in Figure~\ref{fig:merge_SymML}.

\begin{figure}
\begin{alltt}
codatatype 'a inflist = head is 'a & tail is 'a inflist;

fun iseq1() = merge head <= 1
              & tail <= iseq1();
\end{alltt}
\caption{An example of the \texttt{merge} construct in SymML. Here, \texttt{inflist} is a definition of an infinite list, and \texttt{iseq1} is an infinite list of ones.}
\label{fig:merge_SymML}
\end{figure}

In Coq, no such construct exists, and the same is the case for Idris. In the wake of work done by Abel and Pientka\,\citep{Abel13Wellfounded} and Abel, Pientka, Thibodeau, and Setzer\,\citep{Abel13Copatterns}, a construct similar to Hagino's \texttt{merge} has recently been implemented in Agda. This construct is called a \emph{copattern}. By allowing projections on the left-hand side of function definitions, copatterns enable users to define corecursive functions in terms of observations. In effect, coinductive data no longer has to be analyzed with pattern matching, but can more naturally be expressed by the observations that can be made on it.

\subsection{Goals and Contributions}
This project serves as a preparation for our master's thesis, where we plan to implement copatterns and coinductive data defined by observations in Idris. The goals of this project are:

\begin{itemize}
\item To understand the ideas behind copatterns.
\item To understand how copatterns are used in practice, for example by studying Agda.
\item To understand how copatterns can be implemented.
\item To implement a simple functional programming language with copatterns.
\item To understand how the current termination checker in Idris works by implementing a similar termination checker employing the size-change principle\,\citep{LeeJones01SizeChange} for said language.
\end{itemize}

As a result of pursuing these goals, our contributions are:

\begin{itemize}
\item An investigation into whether the intended changes can be implemented in Idris without changing its core type theory.
\item A survey of the literature describing different implementations of the size-change principle. This is done in order to find out whether it is feasible to extend the size-change termination checker in Idris to work as a productivity checker for corecursive function definitions with copatterns. Additionally, existing approaches to productivity checking will be explored, for example the guardedness principle.
\item A proposal for a productivity checking algorithm for corecursive function definitions with copatterns.
\end{itemize}

\subsection{Outline}
In Section~\ref{sec:background}, we describe the core concepts behind coinductive data, copatterns, and productivity. Section~\ref{sec:related_work} provides a survey of the relevant literature, in particular with respect to termination and productivity checking. The implementation of a small functional language with copatterns is described in Section~\ref{sec:implementing-copatterns}. In Section~\ref{sec:productivity}, we present our proposal for a productivity algorithm for corecursive functions with copatterns, while also discussing the virtues of other approaches to productivity checking. Section~\ref{sec:copatterns_in_idris} explains the necessary changes in order for us to add definitions with copatterns to Idris, and finally, Section~\ref{sec:conclusion} provides a conclusion for the entire report.


%!TEX root = forallxsol.tex
%\part{Natural deduction for TFL}
%\label{ch.NDTFL}
%\addtocontents{toc}{\protect\mbox{}\protect\hrulefill\par}

\renewenvironment{proof} %TB: make proofs smaller, since space is a premium here
	{\noindent\par\noindent\small$\begin{nd}}
	{\end{nd}$\noindent\normalsize\ignorespacesafterend}

\setcounter{chapter}{14}
\chapter{Basic rules for TFL}\setcounter{ProbPart}{0}
\problempart
The following two `proofs' are \emph{incorrect}. Explain the mistakes they make.
\begin{multicols}{2}
\begin{proof}
\hypo{abc}{(\enot L \land A) \eor L}
\open
\hypo{nla}{\enot L \eand A}
\have{nl}{\enot L}\ae{nl}
        \have{a}{A}\ae{abc}
\close
\open
        \hypo{l}{L}
        \have{red}{\ered}\ri{l, nl}
        \have{a2}{A}\re{red}
\close
\have{con}{A}\oe{abc, nla-a, l-a2}
\end{proof}
\vfill
\noindent\myanswer{$\eand$E on line 5 can't be applied to line~1, since it is not of the form $\meta{A} \eand \meta{B}$.  `$A$' could be obtained by $\eand$E, but from line~2.}

\myanswer{$\ered$I on line 5 illicitly refers to a line from a closed subproof (line~3).}
\hfill
\columnbreak
\begin{proof}
\hypo{abc}{A \eand (B \eand C)}
\hypo{bcd}{(B \eor C) \eif D}
\have{b}{B}\ae{abc}
\have{bc}{B \eor C}\oi{b}
\have{d}{D}\ce{bc, bcd}
\end{proof}
\vfill
\noindent\myanswer{$\eand$E on line 3 should yield `$B \eand C$'.  `$B$' could then be obtained by $\eand$E again.}

\myanswer{The citation for line 5 is the wrong way round: it should be `$\eif$E 2, 4'.}
\end{multicols}

\problempart
The following three proofs are missing their citations (rule and line numbers). Add them, to turn them into \textit{bona fide} proofs. Additionally, write down the argument that corresponds to each proof.
\newpage
\begin{multicols}{2}
\begin{proof}
\hypo{ps}{P \eand S}
\hypo{nsor}{S \eif R}
\have{p}{P}\ae{ps}
\have{s}{S}\ae{ps}
\have{r}{R}\ce{nsor, s}
\have{re}{R \eor E}\oi{r}
\end{proof}
\\\myanswer{Corresponding argument: \\$P \eand S, S \eif R \therefore R \eor E$}

\bigskip

\begin{proof}
\hypo{ad}{A \eif D}
\open
	\hypo{ab}{A \eand B}
	\have{a}{A}\ae{ab}
	\have{d}{D}\ce{ad, a}
	\have{de}{D \eor E}\oi{d}
\close
\have{conc}{(A \eand B) \eif (D \eor E)}\ci{ab-de}
\end{proof}
\\\myanswer{Corresponding argument: \\$A \eif D \therefore (A \eand B) \eif (D \eor E)$}

\columnbreak

\begin{proof}
\hypo{nlcjol}{\enot L \eif (J \eor L)}
\hypo{nl}{\enot L}
\have{jol}{J \eor L}\ce{nlcjol, nl}
\open
	\hypo{j}{J}
	\have{jj}{J \eand J}\ai{j, j}
	\have{j2}{J}\ae{jj}
\close
\open
	\hypo{l}{L}
	\have{red}{\ered}\ri{l, nl}
	\have{j3}{J}\re{red}
\close
\have{conc}{J}\oe{jol, j-j2, l-j3}
\end{proof}
\\\myanswer{Corresponding argument:\\
$\enot L \eif (J \eor L), \enot L \therefore J$}
\end{multicols}

\solutions
\problempart
\label{pr.solvedTFLproofs}
Give a proof for each of the following arguments:
\begin{earg}
\item $J\eif\enot J \therefore \enot J$
\myanswer{\begin{proof}
\hypo{jnj}{J \eif \enot J}
\open
	\hypo{j}{J}
	\have{nj}{\enot J}\ce{jnj, j}
	\have{red}{\ered}\ri{j, nj}
\close
\have{con}{\enot J}\ni{j-red}
\end{proof}}

\item $Q\eif(Q\eand\enot Q) \therefore \enot Q$
\myanswer{\begin{proof}
\hypo{qq}{Q \eif  (Q \eand \enot Q)}
\open
	\hypo{q}{Q}
	\have{con}{Q \eand \enot Q}\ce{qq, q}
	\have{nq}{\enot Q}\ae{con}
	\have{red}{\ered}\ri{q, nq}
\close
\have{con}{\enot Q}\ni{q-red}
\end{proof}}

\item $A\eif (B\eif C) \therefore (A\eand B)\eif C$
\myanswer{\begin{proof}
\hypo{abc}{A \eif (B \eif C)}
\open
	\hypo{ab}{A \eand B}
	\have{a}{A}\ae{ab}
	\have{bc}{B \eif C}\ce{abc, a}
	\have{b}{B}\ae{ab}
	\have{c}{C}\ce{bc, b}
\close
\have{con}{(A \eand B) \eif C}\ci{ab-c}
\end{proof}}

\item $K\eand L \therefore K\eiff L$
\myanswer{\begin{proof}
\hypo{kl}{K \eand L}
\open
	\hypo{k1}{K}
	\have{l1}{L}\ae{kl}
\close
\open
	\hypo{l2}{L}
	\have{k2}{K}\ae{kl}
\close
\have{con}{K \eiff L}\bi{k1-l1, l2-k2}
\end{proof}}

\item $(C\eand D)\eor E \therefore E\eor D$
\myanswer{\begin{proof}
\hypo{cde}{(C \eand D) \eor E}
\open
	\hypo{cd}{C \eand D}
	\have{d}{D}\ae{cd}
	\have{ed}{E \eor D}\oi{d}
\close
\open
	\hypo{e}{E}
	\have{ed1}{E \eor D}\oi{e}
\close
\have{con}{E \eor D}\oe{cde, cd-ed, e-ed1}
\end{proof}}

\item $A\eiff B, B\eiff C \therefore A\eiff C$
\myanswer{\begin{proof}
\hypo{ab}{A \eiff B}
\hypo{bc}{B \eiff C}
\open
	\hypo{a}{A}
	\have{b}{B}\be{ab, a}
	\have{c}{C}\be{bc, b}
\close
\open
	\hypo{c1}{C}
	\have{b1}{B}\be{bc,c1}
	\have{a1}{A}\be{ab, b1}
\close
\have{con}{A \eiff C}\bi{a-c, c1-a1}
\end{proof}}

\item $\enot F\eif G, F\eif H \therefore G\eor H$
\myanswer{\begin{proof}
\hypo{nfg}{\enot F \eif G}
\hypo{fh}{F \eif H}
\open
        \hypo{ncon}{\enot (G \eor H)}
        \open
                \hypo{f}{F}
                \have{h}{H}\ce{fh, f}
                \have{gh1}{G \eor H}\oi{h}
                \have{bot1}{\ered}\ri{ncon, gh1}
        \close
        \have{nf}{\enot F}\ni{f-bot1}
        \have{g}{G}\ce{nfg,nf}
        \have{gh2}{G \eor H}\oi{g}
        \have{bot2}{\ered}\ri{ncon, gh2}
\close
\have{con}{G \eor H}\ip{ncon-bot2}
\end{proof}}

\item $(Z\eand K) \eor (K\eand M), K \eif D \therefore D$
\myanswer{\begin{proof}
\hypo{zkkm}{(Z \eand K) \eor (K \eand M)}
\hypo{kd}{K \eif D}
\open
	\hypo{zk}{Z \eand K}
	\have{k}{K}\ae{zk}
\close
\open
	\hypo{km}{K \eand M}
	\have{k1}{K}\ae{km}
\close
\have{k2}{K}\oe{zkkm, zk-k, km-k1}
\have{d}{D}\ce{kd, k2}
\end{proof}}

\item $P \eand (Q\eor R), P\eif \enot R \therefore Q\eor E$
\myanswer{\begin{proof}
\hypo{pqr}{P \eand (Q \eor R)}
\hypo{pnr}{P \eif \enot R}
\have{p}{P}\ae{pqr}
\have{nr}{\enot R}\ce{pnr, p}
\have{qr}{Q \eor R}\ae{pqr}
\open
	\hypo{q}{Q}
	\have{qe}{Q \eor E}\oi{q}
\close
\open
	\hypo{r}{R}
	\have{red}{\ered}\ri{r, nr}
	\have{qe1}{Q \eor E}\re{red}
\close
\have{con}{Q \eor E}\oe{qr, q-qe, r-qe1}
\end{proof}}

\newpage
\item $S\eiff T \therefore S\eiff (T\eor S)$
\myanswer{\begin{proof}
\hypo{st}{S \eiff T}
\open
	\hypo{s}{S}
	\have{t}{T}\be{st, s}
	\have{ts}{T \eor S}\oi{t}
\close
\open
	\hypo{ts1}{T \eor S}
	\open
		\hypo{t1}{T}
		\have{s3}{S}\be{st, t1}
	\close
	\open
		\hypo{s1}{S}
		\have{ss}{S \eand S}\ai{s1, s1}
		\have{s2}{S}\ae{ss}
	\close
	\have{s4}{S}\oe{ts1, t1-s3, s1-s2}
\close
\have{con}{S \eiff (T \eor S)}\bi{s-ts, ts1-s4}
\end{proof}}

\item $\enot (P \eif Q) \therefore \enot Q$
\myanswer{\begin{proof}
\hypo{npq}{\enot (P \eif Q)}
\open
	\hypo{q}{Q}
	\open
		\hypo{p}{P}
		\have{qq}{Q \eand Q}\ai{q, q}
		\have{q2}{Q}\ae{qq}
	\close
	\have{pq}{P \eif Q}\ci{p-q2}
	\have{red}{\ered}\ri{pq, npq}
\close
\have{con}{\enot Q}\ni{q-red}
\end{proof}}

\item $\enot (P \eif Q) \therefore P$
\myanswer{\begin{proof}
\hypo{npq}{\enot (P \eif Q)}
\open
	\hypo{np}{\enot P}
	\open
		\hypo{p2}{P}
		\have{red}{\ered}\ri{p2, np}
		\have{q}{Q}\re{red}
	\close
	\have{pq}{P \eif Q}\ci{p2-q}
	\have{red1}{\ered}\ri{pq, npq}
\close
\have{con}{P}\ip{np-red1}
\end{proof}}
\end{earg}

\chapter{Additional rules for TFL}
\label{s:Further}
\setcounter{ProbPart}{0}
\problempart
\label{pr.justifyTFLproof}
The following proofs are missing their citations (rule and line numbers). Add them wherever they are required:
\begin{multicols}{2}
\begin{proof}
\hypo{1}{W \eif \enot B}
\hypo{2}{A \eand W}
\hypo{2b}{B \eor (J \eand K)}
\have{3}{W}\ae{2}
\have{4}{\enot B}\ce{1, 3}
\have{5}{J \eand K}\ds{2b, 4}
\have{6}{K}\ae{5}
\end{proof}
\vfill
\begin{proof}
\hypo{1}{L \eiff \enot O}
\hypo{2}{L \eor \enot O}
\open
	\hypo{a1}{\enot L}
	\have{a2}{\enot O}\ds{2, a1}
	\have{a3}{L}\be{1, a2}
	\have{a4}{\ered}\ri{a3, a1}
\close
\have{3b}{\enot\enot L}\ni{a1-a4}
\have{3}{L}\dne{3b}
\end{proof}
\columnbreak
\begin{proof}
\hypo{1}{Z \eif (C \eand \enot N)}
\hypo{2}{\enot Z \eif (N \eand \enot C)}
\open
	\hypo{a1}{\enot(N \eor  C)}
	\have{a2}{\enot N \eand \enot C}\dem{a1}
	\have{a6}{\enot N}\ae{a2}
	\have{b4}{\enot C}\ae{a2}
		\open
		\hypo{b1}{Z}
		\have{b2}{C \eand \enot N}\ce{1, b1}
		\have{b3}{C}\ae{b2}
		\have{red}{\ered}\ri{b3, b4}
	\close
	\have{a3}{\enot Z}\ni{b1-red}
	\have{a4}{N \eand \enot C}\ce{2,a3}
	\have{a5}{N}\ae{a4}
	\have{a7}{\ered}\ri{a5, a6}
\close
\have{3b}{\enot\enot(N \eor C)}\ni{a1-a7}
\have{3}{N \eor C}\dne{3b}
\end{proof}
\end{multicols}

\problempart
Give a proof for each of these arguments:
\begin{earg}
\item $E\eor F$, $F\eor G$, $\enot F \therefore E \eand G$
\myanswer{\begin{proof}
\hypo{ef}{E \eor F}
\hypo{fg}{F \eor G}
\hypo{nf}{\enot F}
\have{e}{E}\ds{ef, nf}
\have{g}{G}\ds{fg, nf}
\have{eg}{E \eand G}\ai{e, g}
\end{proof}}

\item $M\eor(N\eif M) \therefore \enot M \eif \enot N$
\myanswer{\begin{proof}
\hypo{mnm}{M \eor (N \eif M)}
\open
	\hypo{nm}{\enot M}
	\have{nim}{N \eif M}\ds{mnm, nm}
	\have{nn}{\enot N}\mt{nim, nm}
\close
\have{nminn}{\enot M \eif \enot N}\ci{nm-nn}
\end{proof}}

\item $(M \eor N) \eand (O \eor P)$, $N \eif P$, $\enot P \therefore M\eand O$
\myanswer{\begin{proof}
\hypo{mnop}{(M \eor N) \eand (O \eor P)}
\hypo{nip}{N \eif P}
\hypo{np}{\enot P}
\have{nn}{\enot N}\mt{nip, np}
\have{mn}{M \eor N}\ae{mnop}
\have{m}{M}\ds{mn, nn}
\have{op}{O \eor P}\ae{mnop}
\have{o}{O}\ds{op, np}
\have{mo}{M \eand O}\ai{m, o}
\end{proof}}

\item $(X\eand Y)\eor(X\eand Z)$, $\enot(X\eand D)$, $D\eor M$ \therefore $M$
\myanswer{\begin{proof}
\hypo{xyxz}{(X\eand Y)\eor(X\eand Z)}
\hypo{nxd}{\enot (X \eand D)}
\hypo{dm}{D \eor M}
\open
	\hypo{xy}{X \eand Y}
	\have{x}{X}\ae{xy}
\close
\open
	\hypo{xz}{X \eand Z}
	\have{x2}{X}\ae{xz}
\close
\have{x3}{X}\oe{xyxz, xy-x, xz-x2}
\open
	\hypo{d}{D}
	\have{xd}{X \eand D}\ai{x3, d}
	\have{red}{\ered}\ri{xd, nxd}
\close
\have{nd}{\enot D}\ni{d-red}
\have{m}{M}\ds{dm, nd}
\end{proof}}

\end{earg}

\chapter{Proof-theoretic concepts}
\label{s:ProofTheoreticConcepts}

\setcounter{ProbPart}{0}
\problempart
Show that each of the following sentences is a theorem:
\begin{earg}
\item $O \eif O$
\myanswer{\begin{proof}
\open
	\hypo{o}{O}
	\have{o2}{O}\by{R}{o}
\close
\have{con}{O \eif O}\ci{o-o2}
\end{proof}}
\item $N \eor \enot N$
\myanswer{\begin{proof}
\open
        \hypo{ncon}{\enot (N \eor \enot N)}
        \open
                \hypo{n}{N}
                \have{nnn1}{N \eor \enot N}\oi{n}
                \have{bot1}{\ered}\ri{ncon, nnn1}
        \close
        \have{nn}{\enot N}\ni{n-bot1}
        \have{nnn2}{N \eor \enot N}\oi{nn}
        \have{bot2}{\ered}\ri{ncon, nnn2}
\close
\have{con}{N \eor \enot N}\ip{ncon-bot2}
\end{proof}}

\newpage
\item $J \eiff [J\eor (L\eand\enot L)]$
\myanswer{\begin{proof}
\open
	\hypo{j1}{J}
	\have{jlnl1}{J \eor (L \eand \enot L)}\oi{j1}
\close
\open
	\hypo{jlnl2}{J \eor (L \eand \enot L)}
%	\open
%		\hypo{j2}{J}
%		\have{j3}{J}\by{R}{j2}
%	\close
	\open
		\hypo{lnl}{L \eand \enot L}
		\have{l}{L}\ae{lnl}
		\have{nl}{\enot L}\ae{lnl}
		\have{red}{\ered}\ri{l,nl}
%		\have{j4}{J}\re{red}
	\close
	\have{nlnl}{\enot (L \eand \enot L)}\ni{lnl-red}
	\have{j5}{J}\ds{jlnl2, nlnl}
\close
\have{con}{J \eiff [J\eor (L\eand\enot L)]}\bi{j1-jlnl1, jlnl2-j5}
\end{proof}}
\item $((A \eif B) \eif A) \eif A$
\myanswer{\begin{proof}
\open
	\hypo{aba}{(A \eif B) \eif A}
	\open
		\hypo{na}{\enot A}
		\have{nab}{\enot (A \eif B)}\mt{aba, na}
		\open
			\hypo{a}{A}
			\have{red}{\ered}\ri{a, na}
			\have{b}{B}\re{red}
		\close
		\have{ab}{A \eif B}\ci{a-b}
		\have{red1}{\ered}\ri{ab, nab}
	\close
	\have{a2}{A}\ip{aba-red1}
\close
\have{con}{((A \eif B) \eif A) \eif A}\ci{aba-a2}
\end{proof}}
\end{earg}

\problempart
Provide proofs to show each of the following:
\begin{earg}
\item $C\eif(E\eand G), \enot C \eif G \proves G$
\myanswer{\begin{proof}
\hypo{ceg}{C \eif (E \eand G)}
\hypo{ncg}{\enot C \eif G}
\open
        \hypo{ng}{\enot G}
        \open
                \hypo{c}{C}
                \have{eg}{E \eand G}\ce{ceg, c}
                \have{g1}{G}\ae{eg}
                \have{bot1}{\ered}\ri{ng, g1}
        \close
        \have{nc}{\enot C}\ni{c-bot1}
        \have{g2}{G}\ce{ncg, nc}
        \have{bot2}{\ered}\ri{ng, g2}
\close
\have{con}{G}\ip{ng-bot2}
\end{proof}}

\item $M \eand (\enot N \eif \enot M) \proves (N \eand M) \eor \enot M$
\myanswer{\begin{proof}
\hypo{MnNnM}{M \eand (\enot N \eif \enot M)}
\have{M}{M}\ae{MnNnM}
\have{nNnM}{\enot N \eif \enot M}\ae{MnNnM}
\open
	\hypo{nN}{\enot N}
	\have{nM}{\enot M}\ce{nNnM, nN}
	\have{red}{\ered}\ri{M, nM}
\close
\have{N}{N}\ip{nN-red}
\have{NM}{N \eand M}\ai{N, M}
\have{con}{(N \eand M) \eor \enot M}\oi{NM}
\end{proof}}

\item $(Z\eand K)\eiff(Y\eand M), D\eand(D\eif M) \proves Y\eif Z$
\myanswer{\begin{proof}
\hypo{zkym}{(Z \eand K) \eiff (Y \eand M)}
\hypo{ddm}{D \eand (D \eif M)}
\have{d}{D}\ae{ddm}
\have{dm}{D \eif M}\ae{ddm}
\have{m}{M}\ce{dm, d}
\open
	\hypo{y}{Y}
	\have{ym}{Y \eand M}\ai{y, m}
	\have{zk}{Z \eand K}\be{zkym, ym}
	\have{z}{Z}\ae{zk}
\close
\have{yz}{Y \eif Z}\ci{y-z}
\end{proof}}

\item $(W \eor X) \eor (Y \eor Z), X\eif Y, \enot Z \proves W\eor Y$
\myanswer{\begin{proof}
\hypo{wxyz}{(W \eor X) \eor (Y \eor Z)}
\hypo{xy}{X \eif Y}
\hypo{nz}{\enot Z}
\open
	\hypo{wx}{W \eor X}
	\open
		\hypo{w}{W}
		\have{wy1}{W \eor Y}\oi{w}
	\close
	\open
		\hypo{x}{X}
		\have{y1}{Y}\ce{xy, x}
		\have{wy2}{W \eor Y}\oi{y1}
	\close
	\have{wy3}{W \eor Y}\oe{wx, w-wy1, x-wy2}
\close
\open
	\hypo{yz}{Y \eor Z}
	\have{y}{Y}\ds{yz, nz}
	\have{wy}{W \eor Y}\oi{y}
\close
\have{wy4}{W \eor Y}\oe{wxyz, wx-wy3, yz-wy}
\end{proof}}
\end{earg}

\problempart
Show that each of the following pairs of sentences are provably equivalent: %TB: a bit of a hack here, to try to get the multicols thing working nicer.

\

1. $R \eiff E$, $E \eiff R$
\myanswer{\ignorespaces\begin{multicols}{2}
\begin{proof}
\hypo{re}{R \eiff E}
\open
	\hypo{e}{E}
	\have{r}{R}\be{re, e}
\close
\open
	\hypo{r1}{R}
	\have{e1}{E}\be{re, r1}
\close
\have{con}{E \eiff R}\bi{e-r, r1-e1}
\end{proof}\begin{proof}
\hypo{re}{E \eiff R}
\open
	\hypo{e}{E}
	\have{r}{R}\be{re, e}
\close
\open
	\hypo{r1}{R}
	\have{e1}{E}\be{re, r1}
\close
\have{con}{R \eiff E}\bi{r1-e1, e-r}
\end{proof}
\end{multicols}}
2. $G$, $\enot\enot\enot\enot G$
\myanswer{\begin{multicols}{2}
\begin{proof}
\hypo{g}{G}
\open
	\hypo{nnng}{\enot \enot \enot G}
	\have{ng}{\enot G}\dne{nnng}
	\have{red}{\ered}\ri{g,ng}
\close
\have{nnnng}{\enot\enot\enot\enot G}\ni{nnng-red}
\end{proof}\begin{proof}
\hypo{nnnng}{\enot\enot\enot\enot G}
\have{nng}{\enot \enot G}\dne{nnnng}
\have{g}{G}\dne{nng}
\end{proof}
\end{multicols}}
3. $T\eif S$, $\enot S \eif \enot T$
\myanswer{\begin{multicols}{2}
\begin{proof}
\hypo{ts}{T \eif S}
\open
	\hypo{ns}{\enot S}
	\have{nt}{\enot T}\mt{ts, ns}
\close
\have{nsnt}{\enot S \eif \enot T}\ci{ns-nt}
\end{proof}\begin{proof}
\hypo{nsnt}{\enot S \eif \enot T}
\open
	\hypo{t}{T}
	\open
		\hypo{ns}{\enot S}
		\have{nt}{\enot T}\ce{nsnt, ns}
		\have{red}{\ered}\ri{t, nt}
	\close
	\have{nns}{\enot \enot S}\ni{ns-red}
	\have{s}{S}\dne{nns}
\close
\have{ts}{T \eif S}\ci{t-s}
\end{proof}\end{multicols}}
4. $U \eif I$, $\enot(U \eand \enot I)$
\myanswer{
\begin{multicols}{2}
\begin{proof}
\hypo{ui}{U \eif I}
\open
	\hypo{uni}{U \eand \enot I}
	\have{u}{U}\ae{uni}
	\have{ni}{\enot I}\ae{uni}
	\have{i}{I}\ce{ui, u}
	\have{red}{\ered}\ri{i, ni}
\close
\have{con}{\enot (U \eand \enot I)}\ni{uni-red}
\end{proof}
\begin{proof}
\hypo{con}{\enot (U \eand \enot I)}
\open
	\hypo{u}{U}
	\open
		\hypo{ni}{\enot I}
		\have{uni}{U \eand \enot I}\ai{u, ni}
		\have{red}{\ered}\ri{uni, con}
	\close
	\have{nni}{\enot\enot I}\ni{ni-red}
	\have{i}{I}\dne{nni}
\close
\have{ui}{U \eif I}\ci{u-i}
\end{proof}
\end{multicols}}
\newpage 5. $\enot (C \eif D), C \eand \enot D$
\myanswer{\begin{multicols}{2}
\begin{proof}
\hypo{cnd}{C \eand \enot D}
\have{c}{C}\ae{cnd}
\have{nd}{\enot D}\ae{cnd}
\open
	\hypo{cd}{C \eif D}
	\have{d}{D}\ce{cd, c}
	\have{red}{\ered}\ri{d, nd}
\close
\have{ncd}{\enot (C \eif D)}\ni{cd-red}
\end{proof}
\begin{proof}
\hypo{ncd}{\enot (C \eif D)}
\open
	\hypo{d}{D}
	\open
		\hypo{c}{C}
		\have{d1}{D}\by{R}{d}
	\close
	\have{cd}{C \eif D}\ci{c-d1}
	\have{red}{\ered}\ri{cd, ncd}
\close
\have{nd}{\enot D}\ni{d-red}
\open
	\hypo{nc}{\enot C}
	\open
		\hypo{c1}{C}
		\have{red1}{\ered}\ri{c1, nc}
		\have{d2}{D}\re{red1}
	\close
	\have{cd1}{C \eif D}\ci{c1-d2}
	\have{red2}{\ered}\ri{cd1, ncd}
\close
\have{nnc}{\enot \enot C}\ni{nc-red2}
\have{c2}{C}\dne{nnc}
\have{cnd}{C \eand \enot D}\ai{c2, nd}
\end{proof}
\end{multicols}}
6. $\enot G \eiff H$, $\enot(G \eiff H)$
\myanswer{\begin{multicols}{2}
\begin{proof}
\hypo{ngh}{\enot G \eiff H}
\open
	\hypo{gh}{G \eiff H}
	\open
		\hypo{g}{G}
		\have{h}{H}\be{gh, g}
		\have{ng}{\enot G}\be{ngh, h}
		\have{red}{\ered}\ri{g, ng}
	\close
	\open
		\hypo{ng1}{\enot G}
		\have{h1}{H}\be{ngh, ng1}
		\have{g1}{G}\be{gh, h1}
		\have{red1}{\ered}\ri{g1, ng1}
	\close
	\have{red2}{\ered}\tnd{g-red, ng1-red1}
\close
\have{con}{\enot (G \eiff H)}\ni{gh-red2}
\end{proof}
\begin{proof}
\hypo{ngh}{\enot (G \eiff H)}
\open
	\hypo{ng}{\enot G}
	\open
		\hypo{nh}{\enot H}
		\open
			\hypo{g}{G}
			\have{red}{\ered}\ri{g, ng}
			\have{h}{H}\re{red}
		\close
		\open
			\hypo{h1}{H}
			\have{red1}{\ered}\ri{h1, nh}
			\have{g1}{G}\re{red1}
		\close
		\have{gh}{G \eiff H}\bi{g-h, h1-g1}
		\have{red2}{\ered}\ri{gh, ngh}
	\close
	\have{h2}{H}\ip{nh-red2}
\close
\open
	\hypo{h3}{H}
	\open
		\hypo{g2}{G}
		\open
			\hypo{g4}{G}
			\have{h5}{H}\by{R}{h3}
		\close
		\open
			\hypo{h4}{H}
			\have{g3}{G}\by{R}{g2}
		\close
		\have{gh1}{G \eiff H}\bi{g4-h5, h4-g3}
		\have{red3}{\ered}\ri{gh1, ngh}
	\close
	\have{ng1}{\enot G}\ni{g2-red3}
\close
\have{con}{\enot G \eiff H}\bi{ng-h2, h3-ng1}
\end{proof}
\end{multicols}}

\problempart
If you know that $\meta{A}\proves\meta{B}$, what can you say about $(\meta{A}\eand\meta{C})\proves\meta{B}$? What about $(\meta{A}\eor\meta{C})\proves\meta{B}$? Explain your answers.
\\\myanswer{If $\meta{A} \proves \meta{B}$, then $(\meta{A} \eand \meta{C})\proves \meta{B}$. After all, if $\meta{A} \proves \meta{B}$, then there is some proof with assumption $\meta{A}$ that ends with $\meta{B}$, and no undischarged assumptions other than $\meta{A}$. Now, if we start a proof with assumption $(\meta{A} \eand \meta{C})$, we can obtain $\meta{A}$ by $\eand$E. We can now copy and paste the original proof of $\meta{B}$ from $\meta{A}$, adding 1 to every line number and line number citation. The result will be a proof of $\meta{B}$ from assumption $\meta{A}$.}

\myanswer{However, we cannot prove much from $(\meta{A} \eor \meta{C})$. After all, it might be impossible to prove $\meta{B}$ from $\meta{C}$.}

\

\problempart In this chapter, we claimed that it is just as hard to show that two sentences are not provably equivalent, as it is to show that a sentence is not a theorem. Why did we claim this? (\emph{Hint}: think of a sentence that would be a theorem iff \meta{A} and \meta{B} were provably equivalent.)
\\\myanswer{Consider the sentence $\meta{A} \eiff \meta{B}$. Suppose we can show that this is a theorem. So we can prove it, with no assumptions, in $m$ lines, say. Then if we assume $\meta{A}$ and copy and paste the proof of $\meta{A} \eiff \meta{B}$ (changing the line numbering), we will have a deduction of this shape:
\begin{proof}
\hypo{a}{\meta{A}}
\have[m][1]{m}{\meta{A} \eiff \meta{B}}
\have{b}{\meta{B}}\be{m, a}
\end{proof}
\\This will show that $\meta{A} \proves \meta{B}$. In exactly the same way, we can show that $\meta{B} \proves \meta{A}$. So if we can show that $\meta{A} \eiff \meta{B}$ is a theorem, we can show that $\meta{A}$ and $\meta{B}$ are provably equivalent.}

\myanswer{Conversely, suppose we can show that $\meta{A}$ and $\meta{B}$ are provably equivalent. Then we can prove $\meta{B}$ from the assumption of $\meta{A}$ in $m$ lines, say, and prove $\meta{A}$ from the assumption of $\meta{B}$ in $n$ lines, say. Copying and pasting these proofs together (changing the line numbering where appropriate), we obtain:
\begin{proof}
\open
	\hypo{a}{\meta{A}}
	\have[m]{b1}{\meta{B}}
\close
\open
	\hypo{b}{\meta{B}}
	\have[m+n]{a1}{\meta{A}}
\close
\have{ab}{\meta{A} \eiff \meta{B}}\bi{a-b1, b-a1}
\end{proof}
\\Thus showing that $\meta{A} \eiff \meta{B}$ is a theorem.}

\myanswer{There was nothing special about $\meta{A}$ and $\meta{B}$ in this. So what this shows is that the problem of showing that two sentences are provably equivalent is, essentially, the same problem as showing that a certain kind of sentence (a biconditional) is a theorem.}

\setcounter{chapter}{18}
\chapter{Derived rules}\setcounter{ProbPart}{0}
\problempart
Provide proof schemes that justify the addition of the third and fourth De Morgan rules as derived rules.

\
\\\myanswer{Third rule:
\begin{proof}
		\have[m]{nab}{\enot \meta{A} \eand \enot \meta{B}}
		\have[k]{na}{\enot \meta{A}}\ae{nab}
		\have{nb}{\enot \meta{B}}\ae{nab}
		\open
			\hypo{aob}{\meta{A} \eor \meta{B}}
			\open
				\hypo{a}{\meta{A}}
				\have{con1}{\ered}\ri{a, na}
			\close
			\open
				\hypo{b}{\meta{B}}
				\have{con2}{\ered}\ri{b, nb}
			\close
			\have{con3}{\ered}\oe{aob, a-con1, b-con2}
		\close
		\have{con}{\enot (\meta{A} \eor \meta{B})}\ni{aob-con3}
	\end{proof}}

\
\\\myanswer{Fourth rule:
	\begin{proof}
		\have[m]{nab}{\enot (\meta{A} \eor \meta{B})}
		\open
			\hypo[k]{a}{\meta{A}}
			\have{aob}{\meta{A} \eor \meta{B}}\oi{a}
			\have{nab1}{\ered}\ri{aob, nab}
		\close
		\have{na}{\enot \meta{A}}\ni{a-nab1}
		\open
			\hypo{b}{\meta{B}}
			\have{aob2}{\meta{A} \eor \meta{B}}\oi{b}
			\have{nab2}{\ered}\ri{aob2, nab}
		\close
		\have{nb}{\enot \meta{B}}\ni{b-nab2}
		\have{con}{\enot \meta{A} \eand \enot \meta{B}}\ai{na, nb}
	\end{proof}
}

\problempart
The proofs you offered in response to the practice exercises of \S\S\ref{s:Further}--\ref{s:ProofTheoreticConcepts} used derived rules. Replace the use of derived rules, in such proofs, with only basic rules. You will find some `repetition' in the resulting proofs; in such cases, offer a streamlined proof using only basic rules.  (This will give you a sense, both of the power of derived rules, and of how all the rules interact.)

\setcounter{chapter}{19}
\chapter{Soundness and Completeness}\setcounter{ProbPart}{0}

\practiceproblems
\noindent\problempart Use either a derivation or a truth table for each of the following.
\begin{enumerate}%[label=(\arabic*)]
\item Show that $A \eif [((B \eand C) \eor D) \eif A]$ is a tautology.
\item Show that $A \eif (A \eif B)$ is not a tautology
\item Show that the sentence $A \eif \enot{A}$ is not a contradiction.
\item Show that the sentence $A \eiff \enot A$ is a contradiction.
\item Show that the sentence $ \enot (W \eif (J \eor J)) $ is contingent
\item Show that the sentence $ \enot(X \eor (Y \eor Z)) \eor (X \eor (Y \eor Z))$ is not contingent
 \item Show that the sentence $B \eif \enot S$ is equivalent to the sentence $\enot \enot B \eif \enot S$
\item Show that the sentence $ \enot (X \eor O) $ is not equivalent to the sentence $X \eand O$
\item Show that the sentences $\enot(A \eor B)$, $C$, $C \eif A$  are jointly inconsistent.
\item Show that the sentences $\enot(A \eor B)$, $\enot{B}$, $B \eif A$ are jointly consistent
\item Show that $\enot(A \eor (B \eor C)) $ \therefore $ \enot{C}$ is valid.
\item Show that $\enot(A \eand (B \eor C))$ \therefore $ \enot{C}$ is invalid.
\end{enumerate}

\noindent\problempart Use either a derivation or a truth table for each of the following.
\begin{enumerate}%[label=(\arabic*)]
\item Show that $A \eif (B \eif A)$ is a tautology
\item Show that $\enot (((N \eiff Q) \eor Q) \eor N)$ is not a tautology
\item Show that $ Z \eor (\enot Z \eiff Z) $ is contingent
\item show that $ (L \eiff ((N \eif N) \eif L)) \eor H $ is not contingent
\item Show that $ (A \eiff A) \eand (B \eand \enot B)$ is a contradiction
\item Show that $ (B \eiff (C \eor B)) $ is not a contradiction.
\item Show that $ ((\enot X \eiff X) \eor X) $ is equivalent to $X$
\item Show that $F \eand (K \eand R) $ is not equivalent to $ (F \eiff (K \eiff R)) $
\item Show that the sentences $ \enot (W \eif W)$, $(W \eiff W) \eand W$, $E \eor (W \eif \enot (E \eand W))$ are inconsistent.
\item Show that the sentences  $\enot R \eor C $, $(C \eand R) \eif \enot R$, $(\enot (R \eor R) \eif R) $ are consistent.
\item Show that $\enot \enot (C \eiff \enot C), ((G \eor C) \eor G) \therefore ((G \eif C) \eand G) $ is valid.
\item Show that $ \enot \enot L,  (C \eif \enot L) \eif C) \therefore \enot C$ is invalid.
\end{enumerate}


\section{Gathering}\label{perk:gathering}
\textbf{Cost:} 50 CP\\
\textbf{Requirements:} -\\
\textbf{Skill, Passive, Source(50 Gold), Repeatable}\\
You can use a salvaging knife to scavenge for plants, food, mushrooms and other ingredients when you are scavenging an area.
Doing so requires a PE check, and you can add your crafting level to it.
When doing so, the GM compares your check to the Gathering table of the Biome or Area that you're currently in.\\
You can roll once per 4-hour interval, and the amount and quality of items you find is based on your roll.\\
You can also use your level to gather items that you find in dungeons, towns and other areas, as long as they are not wood, creature parts, or minerals.
\\
Level Progression:\\
II: 150 CP, You can also add 1d4 on gathering checks.\\
III: 350 CP, You can also add 2d4 on gathering checks.\\
IV: 750 CP, You can also add 3d4 on gathering checks.\\