\documentclass[a4paper, 11pt]{article}

%% Language and font encodings
\usepackage[english]{babel}
\usepackage[utf8x]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{libertine}

%% Sets page size and margins
\usepackage[a4paper,top=2cm,bottom=2cm,left=3cm,right=3cm,marginparwidth=1.75cm]{geometry}

%% Useful packages
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage[colorinlistoftodos]{todonotes}
\usepackage[colorlinks=true, allcolors=blue]{hyperref}
\usepackage{booktabs}
\usepackage{multirow}

\title{Problem Set 2}
\author{Huy Le Quang}

\begin{document}
\maketitle

\section {Gross Domestic Product - GDP}

\textbf{Question 1:} Define the GDP verbally. What are the differences between the real and the nominal GDP?

\textbf{Answer:}

Gross Domestic Product - GDP: measures the market value $P_{it}Y_{it}$ of the sum of all final goods and services produced within an economy in a given period of time $t$

Nominal GDP measures the value of the output of the economy at current prices

Real GDP measures the value of the output of the economy using constant prices (i.e the prices of the selected base year) \\

\textbf{Question 2:} Explain why the nominal GDP is not (always) a proper indicator to describe the aggregate economic development.

\textbf{Answer:}

The change in GDP over time could be both due to changes in price level and changes in quantity of products. If we want to know whether economic well--being has increased overtime, nominal GDP using current prices is not an appropriate measure of this issue. \\

\textbf{Question 3:} How is the growth rate of the GDP defined?

\textbf{Answer:}

Growth rate is the increase in the market value of goods and services produced by an economy over time (e.g. from year to year).

 % Table generated by Excel2LaTeX from sheet 'Tabelle1'
\begin{table}[htbp]
  \centering
  \caption{Growth rate in 2009}
    \begin{tabular}{lrr}
    \toprule
    \toprule
    \multicolumn{1}{c}{\textbf{Year}} & \multicolumn{1}{c}{\textbf{2008}} & \multicolumn{1}{c}{\textbf{2009}} \\
    \midrule
    \textbf{Real GDP} &                         2,477.8    &        2,435.9    \\
    \textbf{Growth rate} &       & -1.69\% \\
    \textbf{Growth rate (approx)} &       & -1.71\% \\
    \bottomrule
    \end{tabular}%

\end{table}%

\textbf{Question 4:} Calculation

% Table generated by Excel2LaTeX from sheet 'Tabelle1'
\begin{table}[htbp]
  \centering

    \begin{tabular}{lrr}
    \toprule
    \toprule
          & \multicolumn{1}{c}{\textbf{Apples}} & \multicolumn{1}{c}{\textbf{Orange}} \\
    \midrule
    Q1    & 50    & 100 \\
    P1    & 1     & 0.8 \\
    Q2    & 80    & 120 \\
    P2    & 1.25  & 1.6 \\
    \bottomrule
    \end{tabular}%
  \label{tab:addlabel}%
\end{table}%

\textbf{Answer:}
% Table generated by Excel2LaTeX from sheet 'Tabelle1'
\begin{table}[htbp]
  \centering
  \caption{Nominal, real GDP and growth rate}
    \begin{tabular}{lrr}
    \toprule
    \toprule
          & \multicolumn{1}{c}{\textbf{Year 1}} & \multicolumn{1}{c}{\textbf{Year 2}} \\
    \midrule
    Nominal GDP & 130   & 292 \\
    Real GDP (Year 1 as base) & 130   & 176 \\
    Real GDP (Year 2 as base) & 222.5 & 292 \\
    Growth rate (Year 1 as base) &       & 35.4\% \\
    Growth rate (Year 2 as base) &       & 31.2\% \\
    Geometric mean (Year 1 as base) &       & 0.16 \\
    Geometric mean (Year 2 as base) &       & 0.15 \\
    \bottomrule
    \end{tabular}%

\end{table}%

\section {Macroeconomic Accounting}

\textbf{Question 5:} The GDP can be defined from three different points of view. List the three things the GDP measures.

\textbf{Answer:}

\begin{itemize}
\item Output/Product approach
\item Total Expenditure approach
\item Total Income approach
\end{itemize}

\textbf{Question 6:}: What is the difference between the Gross Domestic Product (GDP) and the Gross National Product (GNP)? What is the difference between the Net Exports (NX) and the Current Account (CA)? What’s going on if $NX>0$ and $CA=0$?

\textbf{Answer:}

GNP = GDP + Factor Payments from Abroad - Factor Payments to Abroad
Current Account = NX + Net Factor Payments from Abroad (NFIA) + unilateral transfer
If $NX>0$ and $CA=0$, then NFIA must be smaller than 0. This means that we export more to abroad than import products from abroad, and at the same time, we receive more payments from abroad to buy our exported products. \\

\textbf{Question 7:} What happens to GDP when the owner of a small firm marries her secretary and stops paying for his work, which he continuous to perform?

\textbf{Answer:}
Nothing changes in GDP because either he pays himself as his salary or the money is retained in his firm's profit. \\

\textbf{Question 8:} I bought my house for €80,000. I have just sold it for €110,000, and the estate agent received a 10\% commission from the buyer. What is the effect on GDP?

\textbf{Answer:}

Increase in GDP $= (110,000-80,000) + 110,000*0.1 = 30,000 + 11,000 = 41,000$ \\

\textbf{Question 9:} Define the term value added.

\textbf{Answer:}

Value added is the difference between the value of the final output sold and the cost of purchasing the raw materials and intermediate goods needed to produce the output. \\

\textbf{Question 10:} A farmer grows a kilo of wheat and sells it to a miller for € 1. The miller turns the wheat into flour and then sells the flour to a baker for €3. The baker uses it to make bread and sells the bread for € 6 to an engineer who eats the bread. What is the value added by each person? What is GDP?

\textbf{Answer:}

Value added if the farmer = €1
Value added of the miller = €2
Value added of the baker = €3
GDP = €6  \\

\textbf{Question 11:} What are the components of aggregate demand?

\textbf{Answer:}

$$AD = C + I + G + X$$ \\

\textbf{Question 12:} Place each of the following transactions in one of the four components of expenditure for the German economy: consumption, investment, government purchases, and net exports: (a) BMW sells a car to a German household; (b) BMW sells a car to a US resident; (c) BMW sells a car to the German government; (d) BMW produces a car to be sold next year.

\textbf{Answer:}
\begin{itemize}
\item a. BMW sells a car to a German household: Consumption
\item b. BMW sells a car to a US resident: Net export
\item c. BMW sells a car to the German government: Government purchases
\item d. BMW produces a car to be sold next year: Investment   \\
\end{itemize}

\textbf{Question 13:} How would the following transactions affect UK net capital outflow?

\textbf{Answer:}

Net capital outflow =  $S^{N} - I$
Net capital outflow = Amount domestic residents are lending to foreigners - Amount foreigners are lending to domestic residents = Outflow - Inflow

\begin{itemize}

\item a. A British mobile telephone company establishes an office in the Czech Republic: Outflow increases, Net capital outflow increases
\item b. An US company’s pension fund buys shares in BP: Inflow increases, Net capital outflow decreases
\item c. Toyota expands its factory in Derby, England: Inflow increases, Net capital outflow decreases
\item d. A London-based investment trust sells its Volkswagen shares to a French investor: Inflow increases, Net capital outflow decreases.
\end{itemize}

\textbf{Question 14:} Holding national saving constant: Does an increase in net capital outflow increase, decrease or have no effect in a country's accumulation of domestic capital (stock)?

\textbf{Answer:}

Net capital outflow = $S^{N} - I$
$\rightarrow I =  S^{N}$ - Net capital outflow
If $S^{N} = const$,
\begin{itemize}
\item Net capital outflow $\uparrow \rightarrow I \downarrow$
\item Net capital outflow $\downarrow \rightarrow I \uparrow$
\end{itemize}

\textbf{Question 15:} Consider the following identity: $S^{P} – I = NX – S^{G}$. Show that the identity holds, explain what the identity means.

\textbf{Answer:}
We have Income = Expenditure
$$C + S^{P} + T = C + I + G + (X - M)$$
$$\rightarrow S^{P} - I = -(T - G) + (X - M)$$
$$\rightarrow S^{P} - I = NX - S^{G}$$

$\rightarrow$ Private net saving = Trade balance - Government saving

\section{Consumer Price Indices, Inflation and Deflation}

\textbf{Question 16:} What does the consumer price index measure? How is it defined, and what is the differences between the CPI and the GDP-Deflator?

\textbf{Answer:}
Consumer Price Index (CPI) measures the current price of a base year basket of goods and services relative to the price of the same basket in the base year

$$CPI_{t} = \frac{\sum_{j}P_{jt}Y_{j0}}{\sum_{j}P_{j0}Y_{j0}}$$

Difference between CPI and GDP Deflator:
\begin{itemize}
\item Deflator measures value of all goods, CPI considers only the goods in the consumer basket.
\item Deflator measures only goods that are domestically produced, imported goods are not considered
\item The CPI uses fixed basket whereas the deflator allows the basket to vary.
\end{itemize}

\textbf{Question 17:} Define the term inflation rate. What is the differences between inflation, deflation and disinflation?

\textbf{Answer:}
Inflation occurs when there is a significant and sustained increase in price index ($\pi>>0$)

Deflation occurs when there is a sustained decrease in consumer prices ($\pi<0$)

Disinflation is the short term slow down in the rate of inflation

\textbf{Question 18:} If the CPI in 2009 is 107 and 108.4 in 2010. Calculate the rate of inflation in 2010.

\textbf{Answer:}

$$ \pi_{2010} = \frac{(108.4 - 107)}{107} = 1.31\%$$

\textbf{Question 19:} Calculation

\textbf{Answer:}
% Table generated by Excel2LaTeX from sheet 'Tabelle1'
\begin{table}[htbp]
  \centering
  \caption{Answer to questions in a and b}
    \begin{tabular}{lrr}
    \toprule
    \toprule
          & \multicolumn{1}{c}{\textbf{2010}} & \multicolumn{1}{c}{\textbf{2015}} \\
    \textbf{Prices} &       &  \\
    \multicolumn{1}{r}{Car} &                           50,000    &            60,000    \\
    \multicolumn{1}{r}{Bread} &                                  10    &                    20    \\
    \textbf{Quantity} &       &  \\
    \multicolumn{1}{r}{Car} &                                100    &                  120    \\
    \multicolumn{1}{r}{Bread} &                        500,000    &          400,000    \\
    \midrule
    Nominal GDP &                   10,000,000    &    15,200,000    \\
    Real GDP &                   10,000,000    &    10,000,000    \\
    GDP deflator &                                100    &                  152    \\
    CPI   &                               1.00    &                1.60    \\
    Price increase (Laspeyres) &       & 60\% \\
    Price increase (Paasche) &       & 52\% \\
    \bottomrule
    \end{tabular}%

c. If the Government wants to index pensions, we should use GDP deflator because pensions is not an item in the consumer basket.
\end{table}%

\textbf{Question 20:} Calculation

\textbf{Answer:}

% Table generated by Excel2LaTeX from sheet 'Tabelle1'
\begin{table}[htbp]
  \centering
  \caption{Answers to questions from a to d}
    \begin{tabular}{lrr}
    \toprule
    \toprule
          & \multicolumn{1}{c}{\textbf{Year 1}} & \multicolumn{1}{c}{\textbf{Year 2}} \\
    \textbf{Prices} &       &  \\
    \multicolumn{1}{r}{Red} & 1     & 2 \\
    \multicolumn{1}{r}{Green} & 2     & 1 \\
    \textbf{Basket} &       &  \\
    \multicolumn{1}{r}{Red} & 10    & 0 \\
    \multicolumn{1}{r}{Green} & 0     & 10 \\
    \midrule
    CPI (Base Year 1) & 1     & 2 \\
    Nominal Spending & 10    & 10 \\
    Real Spending (Base Year 1) & 10    & 20 \\
    Price deflator & 100   & 50 \\
    \bottomrule
    \end{tabular}%
\end{table}%

\clearpage

e. Suppose H is equally happy eating red or green apples. The true cost of living does not change for H because he switches between red and green apple when their prices change.

\textbf{Question 21:} What is the difference between the real and nominal interest rate according to the Fisher equations?

\textbf{Answer:}
\begin{itemize}
\item Nominal interest rate is the interest rate that banks pay
\item Real interest rate is the increase in your purchasing power
\item Fisher equation: $i = r + \pi$
\end{itemize}

\textbf{Question 22:} Define the terms ex-ante and ex-post and give an example.

\textbf{Answer:}

\begin{itemize}
\item Ex-ante is something happens before (EX: expected inflation)
\item Ex-post is something happens after (when something is realized) (EX: realized inflation)
\end{itemize}

\textbf{Question 23:} List different costs of inflation.

\textbf{Answer:}
\begin{itemize}
\item Shoe leather cost
\item Menu cost
\item Inflation induced tax distortions
\end{itemize}

\textbf{Question 24:} Define the term real and nominal variable and give an example of each.

\textbf{Answer:}

\textbf{Question 25:} Statement: Inflation is reallocation of debt. What is meant by this? Does it matter whether the inflation is expected or unexpected? Explain!

\textbf{Answer:}

Example: debtor and creditor enter into a long-term loan agreement. They both expect that inflation is low in the future, so they agree to set a low interest rate on this loan. Suppose that inflation is unexpectedly increasing over the next years, (1) the creditor receives a low interest payment because he already signed the contract and cannot increase the interest rate; (2) the real purchasing power of money is decreasing, which makes it even worse for creditor. In this case, creditor will lose, and debtor will gain. We can imagine a reverse situation if inflation decreases in the future. Therefore, unexpected inflation is a problem because it reallocates the wealth of debtor and creditor. \\

\section{Money and Monetary Aggregates}

\textbf{Question 26:} What is the difference between fiat and commodity money?

\textbf{Answer:}

A fiat money is a legal claim as it attains all its properties from the law.

Commodity money, on the other hand, is money that derives its value from a commodity of which it is made. \\

\textbf{Question 27:} Describe the functions of money in an economy. Which of these functions do the following items (not) satisfy? (a) a credit card; (b) a painting; (c) a bus ticket.

\textbf{Answer:}

Functions of money in the economy:
\begin{itemize}
\item a stock of assets that store values: credit card, bus ticket, painting
\item a unit of account
\item a medium of exchange: painting
\end{itemize}

\textbf{Question 28:} What are open-market operations, and how do they influence the money supply?

\textbf{Answer:}

OMOs are the purchase and sale of non-monetary assets (mainly government bonds)from and to the commercial banks by the central bank to expand or contract the money in the banking system.

To expand the money supply: central bank buys assets and pay them with ``newly'' printed money.

To reduce the money supply: central bank sells assets and receive money (and ``destroy'' it). \\

\textbf{Question 29:} What is the money market? What is the refinancing rate and how is it related to the money market?

\textbf{Answer:}

Money market is where financial instruments with high liquidity and very short maturities are traded.

Refinancing rate is the rate at which commercial banks borrow from the central bank. Normally, these borrowings are extremely short term (overnight), therefore, the transactions happen in the money market.

\textbf{Question 30:} Write down the quantity equation of money and explain it.

\textbf{Answer:}

Quantity equation of money: $M x v = P x Y$

This equation describe how the amount of money M in an economy is related to the number of economic transactions (= the economy's nominal output $PY$). $v$ is the velocity of money (number of times an euro bill changes hands in a given time period). \\

\textbf{Question 31:} Explain how (private) banks create money.

\textbf{Answer:}

In a fractional reserve system, banks create money. Because commercial banks only keep a fraction of their deposits in reserve, and lend out the rest. The next bank receiving this amount of money will continue to keep only a fraction of deposits in reserve and lend out the rest. This process continues, and the total money supply created depends on the reserve ratio: Total money supply = $\frac{1}{rr}$ x Original Deposits. \\

\textbf{Question 32:} What are the various ways in which the central bank can influence the money supply?

\textbf{Answer:}
\begin{itemize}
\item Open market operations
\item Change reserve requirements
\item Change refinancing rate
\end{itemize}

\textbf{Question 33:} Explain how each of the following events changes the money supply (if at all).

\textbf{Answer:}

\begin{itemize}
\item a. The central bank buys bonds in an open market operation: Increase money supply
\item b. The central bank increases the interest rate it pays banks holding reserves: Decrease money supply
\item c. Rumours about a computer virus attack on ATMs increase the amount of money people hold as currency rather than demand deposits: Decrease money supply
\item d. The ECB flies a helicopter over the Frankfurt pedestrian precinct and drops 100 euro bills: Increase money supply
\end{itemize}

\textbf{Question 34:} Why might a banking crisis lead to a fall in money supply?

\textbf{Answer:}
The change in money supply is determined by the (deposit) behavior of households and (lending) behavior of commercial banks. When financial crisis happens, households lose trust in the banking system so they want to hold money (at home) rather than depositing in the banks $\rightarrow$ Money supply falls. Business do not have profitable projects, so they do not need to borrow from banks. If banks cannot lend out money, they cannot create money $\rightarrow$ Money supply falls.

\section{Unemployment}
\textbf{Question 35:} Assume that in the UK in 2010 of all adult people 28,980,000 were employed, 1,116,000 were unemployed and around 10,904,000 were not in the labour force. How big was the labour force? What was the labour force participation rate? What was the unemployment rate?

\textbf{Answer:}
Labor force = $28,980,000 + 1,116,000 = 30,096,000$

Labor force participation rate = $\frac{30,096,000}{30,096,000 + 10,904,000} = 73.4\%$

Unemployment rate = $\frac{1,116,000}{30,096,000} = 3.71\%$

\textbf{Question 36:} Name four different reasons why unemployment may occur and briefly describe the differences between the different kinds of unemployment.

\textbf{Answer:}

\textbf{Question 37:} Give three explanations for wages rigidities – why the real wage rate may remain above the level that equilibrates labour supply and labour demand.

\textbf{Answer:}
\begin{itemize}
\item Minimum wage law
\item Trade union or collective bargaining
\item Efficiency wage
\end{itemize}

\textbf{Question 38:} What causes cyclical unemployment?

\textbf{Answer:}

Cyclical unemployment is a short-run phenomenon that occurs if firms temporarily layoff their workers due to a decline in the production of goods and services during a recession (decline in aggregate demand). \\

\textbf{Question 39:} What is the effect on wages, employment, and unemployment of a wave of immigration: (a) in the absence of minimum wage legislation? (b) in the presence of (a binding) minimum wage legislation?

\textbf{Answer:}

a. In the absence of minimum wage legislation, wages are flexibly changed even in the short run. Assume that immigrants are low-skilled and are perfectly substitutes to natives, a wave of immigration increase labor supply $\rightarrow$ wages decrease. Labor cost is now cheaper, if firms react by expanding production (scale effect), increasing labor demand, then employment may not decrease (or unemployment may not necessarily increase).

b. In the presence of a binding minimum wage legislation, wages are sticky, firms cannot simply reduce wages to take advantage of the increasing labor supply. Therefore, we have excess labor supply, employment does not change, unemployment increases.

\textbf{Question 40:} Suppose that a country experiences a reduction in productivity.

\textbf{Answer:}

\begin{itemize}
\item a. What happens to the labour demand curve? If a country experiences a reduction in productivity, marginal product of labor decreases, so labor demand curve shifts to the left (decreases)
\item b. What is the effect on wages, employment, and unemployment – if the labour market were always in equilibrium? Wages decreases, employment decreases, unemployment increases.
\item c. How would this change in productivity affect the labour market if unions prevented real wages from falling? If wages are not allowed to decrease, we will have excess labor supply, and unemployment still increases.
\end{itemize}

\textbf{Question 41:} Consider an economy with the following Cobb-Douglas production function: $Y = K^{\frac{1}{3}}L^{\frac{2}{3}}$. The economy has 1,000 units of capital and a labour force of 1,000 workers.

\textbf{Answer:}
a. Derive the equation describing labour demand in this economy as a function of the real wage and the capital stock.

b. Assume that the 1,000 units of capital and labour are supplied inelastically. If the real wage is flexible and adjusts to equilibrate supply and demand on the labour market, what is the real wage? In that equilibrium, what are the employment, output and the total amount owned by workers?
c. Now suppose the government passes a law to pay workers a real wage of 1 unit of output. How does this wage compare to the equilibrium wage?
d. What do you think are the effects of this wage?

\textbf{Question 42:} Find the optimal supply of work (= leisure demand) for a real wage of € 20/hr for someone who views consumption and leisure as perfect complements in a 10 to 1 ratio (i.e. she requires 1 hr of leisure for every € 10 of consumption). The maximum amount of leisure is 24 hr.

\textbf{Answer:}

\textbf{Question 43:} Find the optimal supply of work (= leisure demand) for a real wage of € 20/hr for someone who views consumption and leisure as perfect substitutes in a 10 to 1 ratio (i.e. she is willing to sacrifice 1 hr of leisure for € 10 of consumption). The maximum amount of leisure is 24 hr.

\textbf{Answer:}

\textbf{Question 44:} Individual labour supply may be a downward-sloping curve for many individuals, for others it maybe downward sloping but backward-bending at some real-wage level. Why can we still confidentially presume that aggregate labour supply is upward sloping?

\textbf{Answer:}

\textbf{Question 45:} Most countries levy taxes on labour. What is the effect of these taxes on labour supply and equilibrium wages? Assume that workers care for after tax wages only. State your assumptions carefully.

\textbf{Answer:}

\textbf{Question 46:} It is well known in Europe that the unemployment rate among well-educated is con-siderably lower than for those who left school early or without training. Why might this be the case? How might an “education offensive” help solve the unemployment problem, even if wages for the low-skilled are rigid?

\textbf{Answer:}

\textbf{Question 47:} Are the following workers more likely to experience short-term or long-term unem-ployment? Explain.

\textbf{Answer:}
\begin{itemize}
\item a. A construction worker laid off because of bad weather.
\item b. A manufacturing worker who loses her job at a plant in an isolated area.
\item c. A bus industry worker laid off because of competition from the railway.
\item d. An expert welder with little formal education who loses her job when the company installs automatic welding machinery.

\end{itemize}

\textbf{Question 48:} The residents of a certain hall of residence have collected the following data: people who live in the hall can be classified as either involved or uninvolved people, 10 per cent experience a break-up of their relationship every month. Among uninvolved people, 5 percent will enter into a relationship every month. What is the steady-state fraction of residents who are uninvolved?

\textbf{Answer:}

\textbf{Question 49:} Suppose the government passes legislation making it more difficult for firms to fire workers. If the legislation reduces the rate of job separation without affecting the rate of job finding, how would the natural rate of unemployment change?

\textbf{Answer:}

\textbf{Question 50:} In any city at any time, some of the stock of usable office space is vacant. This vacant office space is unemployed capital. How would you explain this phenomenon? Is it a social problem?

\textbf{Answer:}

\section{Exchange rate}

\textbf{Question 51:} Define the terms nominal and real exchange rate. What is the difference between the two expressions?

\textbf{Answer:}

\textbf{Question 52:} What happens to the real exchange rate between two countries if the price level at home doubles, all other things equal (= ceteris paribus)? What if – ceteris paribus – the price of foreign goods doubles? What if – ceteris paribus – the nominal exchange rate doubles?

\textbf{Answer:}

\textbf{Question 53:} What is happening to the Swiss real exchange rate in each of the following situations? Explain.

\textbf{Answer:}
\begin{itemize}
\item a. The Swiss nominal exchange rate is unchanged, but prices rise faster in Switzer-land than abroad.
\item b. The Swiss nominal exchange rate is unchanged, but prices rise faster abroad than in Switzerland.
\item c. The Swiss nominal exchange rate declines, and prices are unchanged in Switzer-land and abroad.
\item d. The Swiss nominal exchange rate declines, and prices rise faster abroad than in Switzerland:
\end{itemize}

\textbf{Question 54:} Suppose a friend tells you that travelling in Mexico is much cheaper now than it was five years ago. ‘Five years ago,’ says your friend, ‘a UK pound bought 10 pesos; this year, a pound buys 15 pesos.’ Is your friend right or wrong? Given that total inflation over this period was about 25 per cent in the United Kingdom and 100 per cent in Mexico, has it become more or less expensive for UK residents to travel in Mexico? Write your answer using a concrete example - such as the price of a British pork pie versus the price of a Mexican taco - that will convince your friend.

\textbf{Answer:}

\textbf{Question 55:} List two goods for which the law of one price is likely to hold, and two goods for which it probably does not hold. Justify your choices.

\textbf{Answer:}

\textbf{Question 56:} A can of lemonade is priced at € 0.75 in Europe and 12 pesos in Mexico. What would the peso-euro exchange rate be if absolute purchasing power parity holds? If a mone-tary expansion caused all prices in Mexico to double, so that lemonade rose to 24 pe-sos, what would happen to the peso-euro exchange rate (if PPP holds)?

\textbf{Answer:}

\textbf{Question 57:} Assume that American rice sells for $1 a kilo, Japanese rice sells for 160 yen a kilo, and the nominal exchange rate is 80 yen per dollar.

\textbf{Answer:}

a. Explain how you could make a profit from this situation. What would be your profit per kilo of rice? If other people exploit the same opportunity, what would happen to the price of rice in Japan and the price of rice in the US?
b. Suppose that rise is the only commodity in the world. What would happen to the real exchange rate between the United States and Japan?

\textbf{Question 58:} How did Bela Balassa and (1928-1991) and Paul Samuelson (1915-2009, Nobel laureate from MIT) explain why wealthier countries are systematically more expensive than poorer ones?

\textbf{Answer:}

\centering
END

\end{document}


\documentclass[a4paper,12pt]{article} % This defines the style of your paper

\usepackage[top = 2.5cm, bottom = 2.5cm, left = 2.5cm, right = 2.5cm]{geometry}
\usepackage[utf8]{inputenc} %utf8 % lettere accentate da tastiera
\usepackage[english]{babel} % lingua del documento
\usepackage[T1]{fontenc} % codifica dei font

\usepackage{multirow} % Multirow is for tables with multiple rows within one
%cell.
\usepackage{booktabs} % For even nicer tables.

\usepackage{graphicx}

\usepackage{setspace}
\setlength{\parindent}{0in}

\usepackage{float}

\usepackage{fancyhdr}

\usepackage{caption}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{mathtools}
\usepackage{color}

\usepackage[hidelinks]{hyperref}
\usepackage{csquotes}
\usepackage{subfigure}

\usepackage{ifxetex,ifluatex}
\usepackage{etoolbox}
\usepackage[svgnames]{xcolor}

\usepackage{tikz}

\usepackage{framed}

 \newcommand*\quotefont{\fontfamily{LinuxLibertineT-LF}} % selects Libertine as
 %the quote font

\newcommand*\quotesize{40} % if quote size changes, need a way to make shifts
%relative
% Make commands for the quotes
\newcommand*{\openquote}
{\tikz[remember picture,overlay,xshift=-4ex,yshift=-1ex]
	\node (OQ)
	{\quotefont\fontsize{\quotesize}{\quotesize}\selectfont``};\kern0pt}

\newcommand*{\closequote}[1]
{\tikz[remember picture,overlay,xshift=4ex,yshift=-1ex]
	\node (CQ) {\quotefont\fontsize{\quotesize}{\quotesize}\selectfont''};}

% select a colour for the shading
\colorlet{shadecolor}{WhiteSmoke}

\newcommand*\shadedauthorformat{\emph} % define format for the author argument

% Now a command to allow left, right and centre alignment of the author
\newcommand*\authoralign[1]{%
	\if#1l
	\def\authorfill{}\def\quotefill{\hfill}
	\else
	\if#1r
	\def\authorfill{\hfill}\def\quotefill{}
	\else
	\if#1c
	\gdef\authorfill{\hfill}\def\quotefill{\hfill}
	\else\typeout{Invalid option}
	\fi
	\fi
	\fi}
% wrap everything in its own environment which takes one argument (author) and
%one optional argument
% specifying the alignment [l, r or c]
%
\newenvironment{shadequote}[2][l]%
{\authoralign{#1}
	\ifblank{#2}
	{\def\shadequoteauthor{}\def\yshift{-2ex}\def\quotefill{\hfill}}
	{\def\shadequoteauthor{\par\authorfill\shadedauthorformat{#2}}\def\yshift{2ex}}
	\begin{snugshade}\begin{quote}\openquote}
		{\shadequoteauthor\quotefill\closequote{\yshift}\end{quote}\end{snugshade}}

\newcommand{\footref}[1]{%
	$^{\ref{#1}}$%
}

\pagestyle{fancy}

\setlength\parindent{24pt}

\fancyhf{}

\lhead{\footnotesize Machine Learning: Assignment 5}

\rhead{\footnotesize Giorgia Adorni}

\cfoot{\footnotesize \thepage}

\begin{document}
%	\thispagestyle{empty}
	\noindent{
	\begin{tabular}{p{15cm}}
		{\large \bf Machine Learning} \\
		Università della Svizzera Italiana \\ Faculty of Informatics \\ \today  \\
		\hline
		\\
	\end{tabular}

	\vspace*{0.3cm}

	\begin{center}
		{\Large \bf Assignment 5: Evolutionary Algorithms}
		\vspace{2mm}

		{\bf Giorgia Adorni (giorgia.adorni@usi.ch)}

	\end{center}
}
	\vspace{0.4cm}

	%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Introduction}
In this assignment, we are going to implement a few evolutionary algorithms against test functions and analyze the characteristics of different algorithms.
Let $f : \mathbb{R}^n \rightarrow \mathbb{R}$ be a test function with n-dimensional domain.

\noindent\textbf{Sphere function}:
	\begin{equation}
		f(\overline{x}) = \sum_{i=1}^nx_i^2 \mbox{.}
	\end{equation}
\textbf{Rastrigin functionction}:
	\begin{equation}
	f(\overline{x}) = An + \sum_{i=1}^n [x_i^2-A \cos(2\pi x_i)]
	\end{equation}
	where $A = 10$. The search domain is constraint as $x_i \in [-5, 5]$.

\section{Test Functions}

In Figure \ref{fig:s} and \ref{fig:r} are shown the 2D contour-plot of 2-dimensional test functions.

\begin{figure}[htb]
	\begin{minipage}[b]{.49\textwidth}
		\centering
		\includegraphics[width=\linewidth]{../src/out/sphere_test.pdf}
		\caption{2D contour plot of 2D Sphere}
		\label{fig:s}
	\end{minipage}
	~
	\begin{minipage}[b]{.49\textwidth}
		\centering
		\includegraphics[width=\linewidth]{../src/out/rastrigin_test.pdf}
		\caption{2D contour plot of 2D Rastrigin}
		\label{fig:r}
	\end{minipage}
\end{figure}

\begin{figure}[htb]
	\begin{minipage}[b]{.49\textwidth}
		\centering
		\includegraphics[width=\linewidth]{../src/out/sphere_test-eval.pdf}
		\caption{Sphere test function evaluation}
		\label{fig:s-eval}
	\end{minipage}
	~
	\begin{minipage}[b]{.49\textwidth}
		\centering
		\includegraphics[width=\linewidth]{../src/out/rastrigin_test-eval.pdf}
		\caption{Rastrigin test function evaluation}
		\label{fig:r-eval}
	\end{minipage}
\end{figure}

For each test function, 100 points has been uniformly sampled in the domain and evaluated with the test function. This points are shown in Figure \ref{fig:s-eval} and \ref{fig:r-eval}.
Filling the contours and showing the colour-map it is easier to see which are the regions of the global optimum. All the points with value close to 0, the ones in purple, belong to the global optimal region.

For the sphere, the points are concentrated in the central region of the figure.

For the rastrigin function evaluate the samples is many more complicated, since the function has many local minima. However, the global optimum is located in the centre of plot. For this reason, it will be seen later that finding the global optimum of this function will be difficult.

\input{cem}
\input{nes}
\input{cmaes}

\section{Benchmarking}
The comparison has been carried out using the following parameters for all algorithms:
{domain size dimension} of 100, 5000 {population size}, 2000 {number of generations}, {elite set ratio of 0.20 and  {learning rate} of 1e-3.
\bigskip

In Figures \ref{fig:best-s} and \ref{fig:best-r} are plotted the comparisons of CEM, NES and CMA-ES for the best fitness.
\bigskip

Regarding the sphere function, both CEM and CMA-ES perform well, while NES is much slower to converge.
Ultimately, CMA-ES is better than CEM for the sphere function with these parameters.

\begin{figure}[H]
	\centering
	\includegraphics[width=.6\linewidth]{../src/out/comparison/sphere/best-comparison.pdf}
	\caption{Comparison of sphere function with algorithm CEM, NES and CMA-ES for the best fitness}
	\label{fig:best-s}
\end{figure}

Regarding the rastrigin function, NES is definitely the worst algorithm. It is not able to converge to the global optimum.
Both CEM and CMA-ES perform well.
Initially, CEM goes down faster to the minimum, although it is not able to converge to 0 with these parameters, remaining only very close to the optimum.
With about 200 iterations, CMA-ES converges to the global optimum, so it is certainly the best algorithm for this test function.

\bigskip

In Figures \ref{fig:best-s} and \ref{fig:best-r} are plotted the comparisons of CEM, NES and CMA-ES for the worst fitness.

\begin{figure}[H]
	\centering
	\includegraphics[width=.6\linewidth]{../src/out/comparison/rastrigin/best-comparison.pdf}
	\caption{Comparison of CEM, NES and CMA-ES for the best rastrigin fitness}
	\label{fig:best-r}
\end{figure}

Regarding the sphere function, the algorithms behave as in the case of best fitness. Both CEM and CMA-ES perform well, while NES is much slower to converge.

\begin{figure}[H]
	\centering
	\includegraphics[width=.6\linewidth]{../src/out/comparison/sphere/worst-comparison.pdf}
	\caption{Comparison of sphere function with algorithm CEM, NES and CMA-ES for the worse fitness}
	\label{fig:worst-s}
\end{figure}

Also for the rastrigin function, the algorithms behave as in the case of best fitness. NES is definitely the worst algorithm. It is not able to converge to the global optimum.
Both CEM and CMA-ES perform well, although CMA-ES converges to the global optimum in about 150 generations.

\begin{figure}[H]
	\centering
	\includegraphics[width=.6\linewidth]{../src/out/comparison/rastrigin/worst-comparison.pdf}
	\caption{Comparison of CEM, NES and CMA-ES for the worse rastrigin fitness}
	\label{fig:worst-r}
\end{figure}

\end{document}


% !Mode:: "TeX:UTF-8"
% !TEX program  = xelatex
\section{Summary}
Mathematical papers have several types, such as research paper, survey article (review paper), referee report, research proposal, etc. Each type of paper has its characteristics, but they have commonalities in terms of writing. Before writing the paper, we need to think about its high-level architecture carefully, which is a good idea to reduce workload and improve work efficiency. When talking about architecture, there are several aspects that we need to pay attention to the target audience, related materials, paper organization, and repeated modification.

\subsection{Target Audience}
The first task in writing a paper is to target the audience, which helps to determine the writing style, content layout, and article focus by considering the breadth of the intended readership. Identifying the audience can be useful when finishing the paper, you can check whether the paper is well-focused by asking yourself why your intended audience should want to read the paper. If this question can be easily answered, it means that your paper concentrates on the main theme; else you might consider altering the aims or re-working on the current result to unify the theme of the paper.

\subsection{Related Materials}
Collecting some writing-related materials, especially with a few closely related documents, can help you not only in understanding the history and development of your research project but also in using the terminology appropriately. Therefore you can highlight keywords and key sentences in other documents, which can be referenced in future writing. Plagiarism is not allowed under any circumstances, but you can just choose a few words or sentences from references and rephrase them under your understanding.

\subsection{Paper Organization}
A standard mathematical paper is generally composed of \emph{title, abstract, introduction, the main body of the article, conclusions, acknowledgments, references, and appendix}. Furthermore, they all have a specific purpose.
\subsubsection{Title}
The title is to describe the main theme of the paper with the least words and the largest information to attract the audience to further read the abstract or the main body of the paper.

\subsubsection{Abstract}
The abstract is to briefly inform the reader of the main content of this paper with the main purpose, thoughts, and results of the paper to keep the interest in reading the main body.

\subsubsection{Introduction}
The introduction should provide a comprehensive, accurate and objective characterization to the background and the development of the issues, which will be discussed in the paper, to give the audience valuable information and good impressions.

\subsubsection{Main Body}
The main body is the most important part of the paper, it comprehensively demonstrates the research results and the analysis of results. The main body of the paper can be composed of various components, which leads to several structures, such as,
\begin{itemize}
	\item preliminaries, main results, the outline of proofs and extensions;
	\item the problem or governing equations, the numerical method or experimental method, theoretical analysis, numerical results, and conclusions.
\end{itemize}

\subsubsection{Conclusions}
The conclusions should provide a summary of the main contribution, explain the questions mentioned in the introduction, point out other aspects or broader issues that the paper does not consider, talk about the possible impact of the research and identify the next step or look to the future.

\subsubsection{Acknowledgments}
Acknowledgments are mainly for the people or institutions which have provided help to paper writing. Moreover, we must thank the institutions that fund the research in most cases.

\subsubsection{References}
The papers and books which are related to the content or cited in the paper should be listed under the name of the references, thus the audience can judge whether the information is familiar and whether it is in line with her interest.

\subsubsection{Appendix}
On the one hand, the appendix satisfies the audience who wants to fully understand the process of theorem inference, on the other hand, the appendix provides some new ideas for those who do not see the proof temporarily. Moreover, the author can add the materials, which are useful for the results, to the appendix, and the reader can do the future work through the appendix. It is a win-win setting.

\subsubsection{Repeated Modification}
When completing the first draft of the paper, it is necessary to repeatedly modify it. When writing the first English paper in life, you should find some people, who have some English writing experience or are native speakers, to modify it again and again. You should carefully ponder the reasons why others modify these sentences, in order to improve your writing level.

\nocite{2013数学之英文写作}
\bibliography{ref}


%\vfill\eject
\chapter{Expressions}
\label{expressionchapter}

\newcommand{\syntax}{{\em Syntax: }}
\newcommand{\semantics}{{\em Semantics: }}

%[Deleted for R5RS because of multiple-value returns. -RK]
%A Scheme expression is a construct that returns a value, such as a
%variable reference, literal, procedure call, or conditional.

Expression types are categorized as {\em primitive} or {\em derived}.
Primitive expression types include variables and procedure calls.
Derived expression types are not semantically primitive, but can instead
be defined as macros.
With the exception of {\cf quasiquote}, whose macro definition is complex,
the derived expressions are classified as library features.
Suitable definitions are given in section~\ref{derivedsection}.

\section{Primitive expression types}
\label{primitivexps}

\subsection{Variable references}\unsection

\begin{entry}{%
\pproto{\hyper{variable}}{\exprtype}}

An expression consisting of a variable\index{variable}
(section~\ref{variablesection}) is a variable reference.  The value of
the variable reference is the value stored in the location to which the
variable is bound.  It is an error to reference an
unbound\index{unbound} variable.

\begin{scheme}
(define x 28)
x   \ev  28%
\end{scheme}
\end{entry}

\subsection{Literal expressions}\unsection
\label{literalsection}

\begin{entry}{%
\proto{quote}{ \hyper{datum}}{\exprtype}
\pproto{\singlequote\hyper{datum}}{\exprtype}
\pproto{\hyper{constant}}{\exprtype}}

{\cf (quote \hyper{datum})} evaluates to \hyper{datum}.\mainschindex{'}
\hyper{Datum}
may be any external representation of a Scheme object (see
section~\ref{externalreps}).  This notation is used to include literal
constants in Scheme code.

\begin{scheme}%
(quote a)                     \ev  a
(quote \sharpsign(a b c))     \ev  \#(a b c)
(quote (+ 1 2))               \ev  (+ 1 2)%
\end{scheme}

{\cf (quote \hyper{datum})} may be abbreviated as
\singlequote\hyper{datum}.  The two notations are equivalent in all
respects.

\begin{scheme}
'a                   \ev  a
'\#(a b c)           \ev  \#(a b c)
'()                  \ev  ()
'(+ 1 2)             \ev  (+ 1 2)
'(quote a)           \ev  (quote a)
''a                  \ev  (quote a)%
\end{scheme}

Numerical constants, string constants, character constants, and boolean
constants evaluate ``to themselves''; they need not be quoted.

\begin{scheme}
'"abc"     \ev  "abc"
"abc"      \ev  "abc"
'145932    \ev  145932
145932     \ev  145932
'\schtrue  \ev  \schtrue
\schtrue   \ev  \schtrue%
\end{scheme}

As noted in section~\ref{storagemodel}, it is an error to alter a constant
(i.e.~the value of a literal expression) using a mutation procedure like
{\cf set-car!}\ or {\cf string-set!}.

\end{entry}

\subsection{Procedure calls}\unsection

\begin{entry}{%
\pproto{(\hyper{operator} \hyperi{operand} \dotsfoo)}{\exprtype}}

A procedure call is written by simply enclosing in parentheses
expressions for the procedure to be called and the arguments to be
passed to it.  The operator and operand expressions are evaluated (in an
unspecified order) and the resulting procedure is passed the resulting
arguments.\mainindex{call}\mainindex{procedure call}
\begin{scheme}%
(+ 3 4)                          \ev  7
((if \schfalse + *) 3 4)         \ev  12%
\end{scheme}

A number of procedures are available as the values of variables in the
initial environment; for example, the addition and multiplication
procedures in the above examples are the values of the variables {\cf +}
and {\cf *}.  New procedures are created by evaluating \lambdaexp{}s
(see section~\ref{lambda}).
\todo{At Friedman's request, flushed mention of other ways.}
% or definitions (see section~\ref{define}).

Procedure calls may return any number of values (see \ide{values} in
section~\ref{proceduresection}).  With the exception of {\cf values}
the procedures available in the initial environment return one
value or, for procedures such as {\cf apply}, pass on the values returned
by a call to one of their arguments.

Procedure calls are also called {\em combinations}.
\mainindex{combination}

\begin{note} In contrast to other dialects of Lisp, the order of
evaluation is unspecified, and the operator expression and the operand
expressions are always evaluated with the same evaluation rules.
\end{note}

\begin{note}
Although the order of evaluation is otherwise unspecified, the effect of
any concurrent evaluation of the operator and operand expressions is
constrained to be consistent with some sequential order of evaluation.
The order of evaluation may be chosen differently for each procedure call.
\end{note}

\begin{note} In many dialects of Lisp, the empty combination, {\tt
()}, is a legitimate expression.  In Scheme, combinations must have at
least one subexpression, so {\tt ()} is not a syntactically valid
expression.  \todo{Dybvig: ``it should be obvious from the syntax.''}
\end{note}

\todo{Freeman:
I think an explanation as to why evaluation order is not specified
should be included.  It should not include any reference to parallel
evaluation.  Does any existing compiler generate better code because
the evaluation order is unspecified?  Clinger: yes: T3, MacScheme v2,
probably MIT Scheme and Chez Scheme.  But that's not the main reason
for leaving the order unspecified.}

\end{entry}

\subsection{Procedures}\unsection
\label{lamba}

\begin{entry}{%
\proto{lambda}{ \hyper{formals} \hyper{body}}{\exprtype}}

\syntax
\hyper{Formals} should be a formal arguments list as described below,
and \hyper{body} should be a sequence of one or more expressions.

\semantics
\vest A \lambdaexp{} evaluates to a procedure.  The environment in
effect when the \lambdaexp{} was evaluated is remembered as part of the
procedure.  When the procedure is later called with some actual
arguments, the environment in which the \lambdaexp{} was evaluated will
be extended by binding the variables in the formal argument list to
fresh locations, the corresponding actual argument values will be stored
in those locations, and the expressions in the body of the \lambdaexp{}
will be evaluated sequentially in the extended environment.
The result(s) of the last expression in the body will be returned as
the result(s) of the procedure call.

\begin{scheme}
(lambda (x) (+ x x))      \ev  {\em{}a procedure}
((lambda (x) (+ x x)) 4)  \ev  8

(define reverse-subtract
  (lambda (x y) (- y x)))
(reverse-subtract 7 10)         \ev  3

(define add4
  (let ((x 4))
    (lambda (y) (+ x y))))
(add4 6)                        \ev  10%
\end{scheme}

\hyper{Formals} should have one of the following forms:

\begin{itemize}
\item {\tt(\hyperi{variable} \dotsfoo)}:
The procedure takes a fixed number of arguments; when the procedure is
called, the arguments will be stored in the bindings of the
corresponding variables.

\item \hyper{variable}:
The procedure takes any number of arguments; when the procedure is
called, the sequence of actual arguments is converted into a newly
allocated list, and the list is stored in the binding of the
\hyper{variable}.

\item {\tt(\hyperi{variable} \dotsfoo{} \hyper{variable$_{n}$}\ {\bf.}\
\hyper{variable$_{n+1}$})}:
If a space-delimited period precedes the last variable, then
the procedure takes $n$ or more arguments, where $n$ is the
number of formal arguments before the period (there must
be at least one).
The value stored in the binding of the last variable will be a
newly allocated
list of the actual arguments left over after all the other actual
arguments have been matched up against the other formal arguments.
\end{itemize}

It is an error for a \hyper{variable} to appear more than once in
\hyper{formals}.

\begin{scheme}
((lambda x x) 3 4 5 6)          \ev  (3 4 5 6)
((lambda (x y . z) z)
 3 4 5 6)                       \ev  (5 6)%
\end{scheme}

Each procedure created as the result of evaluating a \lambdaexp{} is
(conceptually) tagged
with a storage location, in order to make \ide{eqv?} and
\ide{eq?} work on procedures (see section~\ref{equivalencesection}).

\end{entry}

\subsection{Conditionals}\unsection

\begin{entry}{%
\proto{if}{ \hyper{test} \hyper{consequent} \hyper{alternate}}{\exprtype}
\rproto{if}{ \hyper{test} \hyper{consequent}}{\exprtype}}  %\/ if hyper = italic

\syntax
\hyper{Test}, \hyper{consequent}, and \hyper{alternate} may be arbitrary
expressions.

\semantics
An {\cf if} expression is evaluated as follows: first,
\hyper{test} is evaluated.  If it yields a true value\index{true} (see
section~\ref{booleansection}), then \hyper{consequent} is evaluated and
its value(s) is(are) returned.  Otherwise \hyper{alternate} is evaluated and its
value(s) is(are) returned.  If \hyper{test} yields a false value and no
\hyper{alternate} is specified, then the result of the expression is
unspecified.

\begin{scheme}
(if (> 3 2) 'yes 'no)           \ev  yes
(if (> 2 3) 'yes 'no)           \ev  no
(if (> 3 2)
    (- 3 2)
    (+ 3 2))                    \ev  1%
\end{scheme}

\end{entry}

\subsection{Assignments}\unsection
\label{assignment}

\begin{entry}{%
\proto{set!}{ \hyper{variable} \hyper{expression}}{\exprtype}}

\hyper{Expression} is evaluated, and the resulting value is stored in
the location to which \hyper{variable} is bound.  \hyper{Variable} must
be bound either in some region\index{region} enclosing the {\cf set!}\ expression
or at top level.  The result of the {\cf set!} expression is
unspecified.

\begin{scheme}
(define x 2)
(+ x 1)                 \ev  3
(set! x 4)              \ev  \unspecified
(+ x 1)                 \ev  5%
\end{scheme}

\end{entry}

\section{Derived expression types}
\label{derivedexps}

The constructs in this section are hygienic, as discussed in
section~\ref{macrosection}.
For reference purposes, section~\ref{derivedsection} gives macro definitions
that will convert most of the constructs described in this section
into the primitive constructs described in the previous section.

\todo{Mention that no definition of backquote is provided?}

\subsection{Conditionals}\unsection

\begin{entry}{%
\proto{cond}{ \hyperi{clause} \hyperii{clause} \dotsfoo}{library \exprtype}}

\syntax
Each \hyper{clause} should be of the form
\begin{scheme}
(\hyper{test} \hyperi{expression} \dotsfoo)%
\end{scheme}
where \hyper{test} is any expression.  Alternatively, a \hyper{clause} may be
of the form
\begin{scheme}
(\hyper{test} => \hyper{expression})%
\end{scheme}
The last \hyper{clause} may be
an ``else clause,'' which has the form
\begin{scheme}
(else \hyperi{expression} \hyperii{expression} \dotsfoo)\rm.%
\end{scheme}
\mainschindex{else}
\mainschindex{=>}

\semantics
A {\cf cond} expression is evaluated by evaluating the \hyper{test}
expressions of successive \hyper{clause}s in order until one of them
evaluates to a true value\index{true} (see
section~\ref{booleansection}).  When a \hyper{test} evaluates to a true
value, then the remaining \hyper{expression}s in its \hyper{clause} are
evaluated in order, and the result(s) of the last \hyper{expression} in the
\hyper{clause} is(are) returned as the result(s) of the entire {\cf cond}
expression.  If the selected \hyper{clause} contains only the
\hyper{test} and no \hyper{expression}s, then the value of the
\hyper{test} is returned as the result.  If the selected \hyper{clause} uses the
\ide{=>} alternate form, then the \hyper{expression} is evaluated.
Its value must be a procedure that accepts one argument; this procedure is then
called on the value of the \hyper{test} and the value(s) returned by this
procedure is(are) returned by the {\cf cond} expression.
If all \hyper{test}s evaluate
to false values, and there is no else clause, then the result of
the conditional expression is unspecified; if there is an else
clause, then its \hyper{expression}s are evaluated, and the value(s) of
the last one is(are) returned.

\begin{scheme}
(cond ((> 3 2) 'greater)
      ((< 3 2) 'less))         \ev  greater%

(cond ((> 3 3) 'greater)
      ((< 3 3) 'less)
      (else 'equal))            \ev  equal%

(cond ((assv 'b '((a 1) (b 2))) => cadr)
      (else \schfalse{}))         \ev  2%
\end{scheme}

\end{entry}

\begin{entry}{%
\proto{case}{ \hyper{key} \hyperi{clause} \hyperii{clause} \dotsfoo}{library \exprtype}}

\syntax
\hyper{Key} may be any expression.  Each \hyper{clause} should have
the form
\begin{scheme}
((\hyperi{datum} \dotsfoo) \hyperi{expression} \hyperii{expression} \dotsfoo)\rm,%
\end{scheme}
where each \hyper{datum} is an external representation of some object.
All the \hyper{datum}s must be distinct.
The last \hyper{clause} may be an ``else clause,'' which has the form
\begin{scheme}
(else \hyperi{expression} \hyperii{expression} \dotsfoo)\rm.%
\end{scheme}
\schindex{else}

\semantics
A {\cf case} expression is evaluated as follows.  \hyper{Key} is
evaluated and its result is compared against each \hyper{datum}.  If the
result of evaluating \hyper{key} is equivalent (in the sense of
{\cf eqv?}; see section~\ref{eqv?}) to a \hyper{datum}, then the
expressions in the corresponding \hyper{clause} are evaluated from left
to right and the result(s) of the last expression in the \hyper{clause} is(are)
returned as the result(s) of the {\cf case} expression.  If the result of
evaluating \hyper{key} is different from every \hyper{datum}, then if
there is an else clause its expressions are evaluated and the
result(s) of the last is(are) the result(s) of the {\cf case} expression;
otherwise the result of the {\cf case} expression is unspecified.

\begin{scheme}
(case (* 2 3)
  ((2 3 5 7) 'prime)
  ((1 4 6 8 9) 'composite))     \ev  composite
(case (car '(c d))
  ((a) 'a)
  ((b) 'b))                     \ev  \unspecified
(case (car '(c d))
  ((a e i o u) 'vowel)
  ((w y) 'semivowel)
  (else 'consonant))            \ev  consonant%
\end{scheme}

\end{entry}

\begin{entry}{%
\proto{and}{ \hyperi{test} \dotsfoo}{library \exprtype}}

The \hyper{test} expressions are evaluated from left to right, and the
value of the first expression that evaluates to a false value (see
section~\ref{booleansection}) is returned.  Any remaining expressions
are not evaluated.  If all the expressions evaluate to true values, the
value of the last expression is returned.  If there are no expressions
then \schtrue{} is returned.

\begin{scheme}
(and (= 2 2) (> 2 1))           \ev  \schtrue
(and (= 2 2) (< 2 1))           \ev  \schfalse
(and 1 2 'c '(f g))             \ev  (f g)
(and)                           \ev  \schtrue%
\end{scheme}

\end{entry}

\begin{entry}{%
\proto{or}{ \hyperi{test} \dotsfoo}{library \exprtype}}

The \hyper{test} expressions are evaluated from left to right, and the value of the
first expression that evaluates to a true value (see
section~\ref{booleansection}) is returned.  Any remaining expressions
are not evaluated.  If all expressions evaluate to false values, the
value of the last expression is returned.  If there are no
expressions then \schfalse{} is returned.

\begin{scheme}
(or (= 2 2) (> 2 1))            \ev  \schtrue
(or (= 2 2) (< 2 1))            \ev  \schtrue
(or \schfalse \schfalse \schfalse) \ev  \schfalse
(or (memq 'b '(a b c))
    (/ 3 0))                    \ev  (b c)%
\end{scheme}

\end{entry}

\subsection{Binding constructs}

The three binding constructs {\cf let}, {\cf let*}, and {\cf letrec}
give Scheme a block structure, like Algol 60.  The syntax of the three
constructs is identical, but they differ in the regions\index{region} they establish
for their variable bindings.  In a {\cf let} expression, the initial
values are computed before any of the variables become bound; in a
{\cf let*} expression, the bindings and evaluations are performed
sequentially; while in a {\cf letrec} expression, all the bindings are in
effect while their initial values are being computed, thus allowing
mutually recursive definitions.

\begin{entry}{%
\proto{let}{ \hyper{bindings} \hyper{body}}{library \exprtype}}

\syntax
\hyper{Bindings} should have the form
\begin{scheme}
((\hyperi{variable} \hyperi{init}) \dotsfoo)\rm,%
\end{scheme}
where each \hyper{init} is an expression, and \hyper{body} should be a
sequence of one or more expressions.  It is
an error for a \hyper{variable} to appear more than once in the list of variables
being bound.

\semantics
The \hyper{init}s are evaluated in the current environment (in some
unspecified order), the \hyper{variable}s are bound to fresh locations
holding the results, the \hyper{body} is evaluated in the extended
environment, and the value(s) of the last expression of \hyper{body}
is(are) returned.  Each binding of a \hyper{variable} has \hyper{body} as its
region.\index{region}

\begin{scheme}
(let ((x 2) (y 3))
  (* x y))                      \ev  6

(let ((x 2) (y 3))
  (let ((x 7)
        (z (+ x y)))
    (* z x)))                   \ev  35%
\end{scheme}

See also named {\cf let}, section \ref{namedlet}.

\end{entry}

\begin{entry}{%
\proto{let*}{ \hyper{bindings} \hyper{body}}{library \exprtype}}\nobreak

\nobreak
\syntax
\hyper{Bindings} should have the form
\begin{scheme}
((\hyperi{variable} \hyperi{init}) \dotsfoo)\rm,%
\end{scheme}
and \hyper{body} should be a sequence of
one or more expressions.

\semantics
{\cf Let*} is similar to {\cf let}, but the bindings are performed
sequentially from left to right, and the region\index{region} of a binding indicated
by {\cf(\hyper{variable} \hyper{init})} is that part of the {\cf let*}
expression to the right of the binding.  Thus the second binding is done
in an environment in which the first binding is visible, and so on.

\begin{scheme}
(let ((x 2) (y 3))
  (let* ((x 7)
         (z (+ x y)))
    (* z x)))             \ev  70%
\end{scheme}

\end{entry}

\begin{entry}{%
\proto{letrec}{ \hyper{bindings} \hyper{body}}{library \exprtype}}

\syntax
\hyper{Bindings} should have the form
\begin{scheme}
((\hyperi{variable} \hyperi{init}) \dotsfoo)\rm,%
\end{scheme}
and \hyper{body} should be a sequence of
one or more expressions. It is an error for a \hyper{variable} to appear more
than once in the list of variables being bound.

\semantics
The \hyper{variable}s are bound to fresh locations holding undefined
values, the \hyper{init}s are evaluated in the resulting environment (in
some unspecified order), each \hyper{variable} is assigned to the result
of the corresponding \hyper{init}, the \hyper{body} is evaluated in the
resulting environment, and the value(s) of the last expression in
\hyper{body} is(are) returned.  Each binding of a \hyper{variable} has the
entire {\cf letrec} expression as its region\index{region}, making it possible to
define mutually recursive procedures.

\begin{scheme}
%(letrec ((x 2) (y 3))
%  (letrec ((foo (lambda (z) (+ x y z))) (x 7))
%    (foo 4)))                   \ev  14
%
(letrec ((even?
          (lambda (n)
            (if (zero? n)
                \schtrue
                (odd? (- n 1)))))
         (odd?
          (lambda (n)
            (if (zero? n)
                \schfalse
                (even? (- n 1))))))
  (even? 88))
		\ev  \schtrue%
\end{scheme}

One restriction on {\cf letrec} is very important: it must be possible
to evaluate each \hyper{init} without assigning or referring to the value of any
\hyper{variable}.  If this restriction is violated, then it is an error.  The
restriction is necessary because Scheme passes arguments by value rather than by
name.  In the most common uses of {\cf letrec}, all the \hyper{init}s are
\lambdaexp{}s and the restriction is satisfied automatically.

% \todo{use or uses?  --- Jinx.}

\end{entry}

\subsection{Sequencing}\unsection

\begin{entry}{%
\proto{begin}{ \hyperi{expression} \hyperii{expression} \dotsfoo}{library \exprtype}}

The \hyper{expression}s are evaluated sequentially from left to right,
and the value(s) of the last \hyper{expression} is(are) returned.  This
expression type is used to sequence side effects such as input and
output.

\begin{scheme}
(define x 0)

(begin (set! x 5)
       (+ x 1))                  \ev  6

(begin (display "4 plus 1 equals ")
       (display (+ 4 1)))      \ev  \unspecified
 \>{\em and prints}  4 plus 1 equals 5%
\end{scheme}

\end{entry}

\subsection{Iteration}%\unsection

\noindent%
\pproto{(do ((\hyperi{variable} \hyperi{init} \hyperi{step})}{library \exprtype}
\mainschindex{do}{\tt\obeyspaces%
     \dotsfoo)\\
    (\hyper{test} \hyper{expression} \dotsfoo)\\
  \hyper{command} \dotsfoo)}

{\cf Do} is an iteration construct.  It specifies a set of variables to
be bound, how they are to be initialized at the start, and how they are
to be updated on each iteration.  When a termination condition is met,
the loop exits after evaluating the \hyper{expression}s.

{\cf Do} expressions are evaluated as follows:
The \hyper{init} expressions are evaluated (in some unspecified order),
the \hyper{variable}s are bound to fresh locations, the results of the
\hyper{init} expressions are stored in the bindings of the
\hyper{variable}s, and then the iteration phase begins.

\vest Each iteration begins by evaluating \hyper{test}; if the result is
false (see section~\ref{booleansection}), then the \hyper{command}
expressions are evaluated in order for effect, the \hyper{step}
expressions are evaluated in some unspecified order, the
\hyper{variable}s are bound to fresh locations, the results of the
\hyper{step}s are stored in the bindings of the
\hyper{variable}s, and the next iteration begins.

\vest If \hyper{test} evaluates to a true value, then the
\hyper{expression}s are evaluated from left to right and the value(s) of
the last \hyper{expression} is(are) returned.  If no \hyper{expression}s
are present, then the value of the {\cf do} expression is unspecified.

\vest The region\index{region} of the binding of a \hyper{variable}
consists of the entire {\cf do} expression except for the \hyper{init}s.
It is an error for a \hyper{variable} to appear more than once in the
list of {\cf do} variables.

\vest A \hyper{step} may be omitted, in which case the effect is the
same as if {\cf(\hyper{variable} \hyper{init} \hyper{variable})} had
been written instead of {\cf(\hyper{variable} \hyper{init})}.

\begin{scheme}
(do ((vec (make-vector 5))
     (i 0 (+ i 1)))
    ((= i 5) vec)
  (vector-set! vec i i))          \ev  \#(0 1 2 3 4)

(let ((x '(1 3 5 7 9)))
  (do ((x x (cdr x))
       (sum 0 (+ sum (car x))))
      ((null? x) sum)))             \ev  25%
\end{scheme}

%\end{entry}

\begin{entry}{%
\rproto{let}{ \hyper{variable} \hyper{bindings} \hyper{body}}{library \exprtype}}

\label{namedlet}
``Named {\cf let}'' is a variant on the syntax of \ide{let} which provides
a more general looping construct than {\cf do} and may also be used to express
recursions.
It has the same syntax and semantics as ordinary {\cf let}
except that \hyper{variable} is bound within \hyper{body} to a procedure
whose formal arguments are the bound variables and whose body is
\hyper{body}.  Thus the execution of \hyper{body} may be repeated by
invoking the procedure named by \hyper{variable}.

%                                              |  <-- right margin
\begin{scheme}
(let loop ((numbers '(3 -2 1 6 -5))
           (nonneg '())
           (neg '()))
  (cond ((null? numbers) (list nonneg neg))
        ((>= (car numbers) 0)
         (loop (cdr numbers)
               (cons (car numbers) nonneg)
               neg))
        ((< (car numbers) 0)
         (loop (cdr numbers)
               nonneg
               (cons (car numbers) neg))))) %
  \lev  ((6 1 3) (-5 -2))%
\end{scheme}

\end{entry}

\subsection{Delayed evaluation}\unsection

\begin{entry}{%
\proto{delay}{ \hyper{expression}}{library \exprtype}}

\todo{Fix.}

The {\cf delay} construct is used together with the procedure \ide{force} to
implement \defining{lazy evaluation} or \defining{call by need}.
{\tt(delay~\hyper{expression})} returns an object called a
\defining{promise} which at some point in the future may be asked (by
the {\cf force} procedure) \todo{Bartley's white lie; OK?} to evaluate
\hyper{expression}, and deliver the resulting value.
The effect of \hyper{expression} returning multiple values
is unspecified.

See the description of {\cf force} (section~\ref{force}) for a
more complete description of {\cf delay}.

\end{entry}

\subsection{Quasiquotation}\unsection
\label{quasiquotesection}

\begin{entry}{%
\proto{quasiquote}{ \hyper{qq template}}{\exprtype} \nopagebreak
\pproto{\backquote\hyper{qq template}}{\exprtype}}

``Backquote'' or ``quasiquote''\index{backquote} expressions are useful
for constructing a list or vector structure when most but not all of the
desired structure is known in advance.  If no
commas\index{comma} appear within the \hyper{qq template}, the result of
evaluating
\backquote\hyper{qq template} is equivalent to the result of evaluating
\singlequote\hyper{qq template}.  If a comma\mainschindex{,} appears within the
\hyper{qq template}, however, the expression following the comma is
evaluated (``unquoted'') and its result is inserted into the structure
instead of the comma and the expression.  If a comma appears followed
immediately by an at-sign (\atsign),\mainschindex{,@} then the following
expression must evaluate to a list; the opening and closing parentheses
of the list are then ``stripped away'' and the elements of the list are
inserted in place of the comma at-sign expression sequence.  A comma
at-sign should only appear within a list or vector \hyper{qq template}.

% struck: "(in the sense of {\cf equal?})" after "equivalent"

\begin{scheme}
`(list ,(+ 1 2) 4)  \ev  (list 3 4)
(let ((name 'a)) `(list ,name ',name)) %
          \lev  (list a (quote a))
`(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b) %
          \lev  (a 3 4 5 6 b)
`(({\cf foo} ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons))) %
          \lev  ((foo 7) . cons)
`\#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8) %
          \lev  \#(10 5 2 4 3 8)%
\end{scheme}

Quasiquote forms may be nested.  Substitutions are made only for
unquoted components appearing at the same nesting level
as the outermost backquote.  The nesting level increases by one inside
each successive quasiquotation, and decreases by one inside each
unquotation.

\begin{scheme}
`(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f) %
          \lev  (a `(b ,(+ 1 2) ,(foo 4 d) e) f)
(let ((name1 'x)
      (name2 'y))
  `(a `(b ,,name1 ,',name2 d) e)) %
          \lev  (a `(b ,x ,'y d) e)%
\end{scheme}

The two notations
 \backquote\hyper{qq template} and {\tt (quasiquote \hyper{qq template})}
 are identical in all respects.
 {\cf,\hyper{expression}} is identical to {\cf (unquote \hyper{expression})},
 and
 {\cf,@\hyper{expression}} is identical to {\cf (unquote-splicing \hyper{expression})}.
The external syntax generated by \ide{write} for two-element lists whose
car is one of these symbols may vary between implementations.
\mainschindex{`}

\begin{scheme}
(quasiquote (list (unquote (+ 1 2)) 4)) %
          \lev  (list 3 4)
'(quasiquote (list (unquote (+ 1 2)) 4)) %
          \lev  `(list ,(+ 1 2) 4)
     {\em{}i.e.,} (quasiquote (list (unquote (+ 1 2)) 4))%
\end{scheme}

Unpredictable behavior can result if any of the symbols
\ide{quasiquote}, \ide{unquote}, or \ide{unquote-splicing} appear in
positions within a \hyper{qq template} otherwise than as described above.

\end{entry}

\section{Macros}
\label{macrosection}

Scheme programs can define and use new derived expression types,
 called {\em macros}.\mainindex{macro}
Program-defined expression types have the syntax
\begin{scheme}
(\hyper{keyword} {\hyper{datum}} ...)%
\end{scheme}%
where \hyper{keyword} is an identifier that uniquely determines the
expression type.  This identifier is called the {\em syntactic
keyword}\index{syntactic keyword}, or simply {\em
keyword}\index{keyword}, of the macro\index{macro keyword}.  The
number of the \hyper{datum}s, and their syntax, depends on the
expression type.

Each instance of a macro is called a {\em use}\index{macro use}
of the macro.
The set of rules that specifies
how a use of a macro is transcribed into a more primitive expression
is called the {\em transformer}\index{macro transformer}
of the macro.

The macro definition facility consists of two parts:

\begin{itemize}
\item A set of expressions used to establish that certain identifiers
are macro keywords, associate them with macro transformers, and control
the scope within which a macro is defined, and

\item a pattern language for specifying macro transformers.
\end{itemize}

The syntactic keyword of a macro may shadow variable bindings, and local
variable bindings may shadow keyword bindings.  \index{keyword}  All macros
defined using the pattern language  are ``hygienic'' and ``referentially
transparent'' and thus preserve Scheme's lexical scoping~\cite{Kohlbecker86,
hygienic,Bawden88,macrosthatwork,syntacticabstraction}:
\mainindex{hygienic}
\mainindex{referentially transparent}

\begin{itemize}

\item If a macro transformer inserts a binding for an identifier
(variable or keyword), the identifier will in effect be renamed
throughout its scope to avoid conflicts with other identifiers.
Note that a \ide{define} at top level may or may not introduce a binding;
see section~\ref{defines}.

\item If a macro transformer inserts a free reference to an
identifier, the reference refers to the binding that was visible
where the transformer was specified, regardless of any local
bindings that may surround the use of the macro.

\end{itemize}

%The low-level facility permits non-hygienic macros to be written,
%and may be used to implement the high-level pattern language.

% The fourth section describes some features that would make the
% low-level macro facility easier to use directly.

\subsection{Binding constructs for syntactic keywords}
\label{bindsyntax}

{\cf Let-syntax} and {\cf letrec-syntax} are
analogous to {\cf let} and {\cf letrec}, but they bind
syntactic keywords to macro transformers instead of binding variables
to locations that contain values.  Syntactic keywords may also be
bound at top level; see section~\ref{define-syntax}.

\begin{entry}{%
\proto{let-syntax}{ \hyper{bindings} \hyper{body}}{\exprtype}}

\syntax
\hyper{Bindings} should have the form
\begin{scheme}
((\hyper{keyword} \hyper{transformer spec}) \dotsfoo)%
\end{scheme}
Each \hyper{keyword} is an identifier,
each \hyper{transformer spec} is an instance of {\cf syntax-rules}, and
\hyper{body} should be a sequence of one or more expressions.  It is an error
for a \hyper{keyword} to appear more than once in the list of keywords
being bound.

\semantics
The \hyper{body} is expanded in the syntactic environment
obtained by extending the syntactic environment of the
{\cf let-syntax} expression with macros whose keywords are
the \hyper{keyword}s, bound to the specified transformers.
Each binding of a \hyper{keyword} has \hyper{body} as its region.

\begin{scheme}
(let-syntax ((when (syntax-rules ()
                     ((when test stmt1 stmt2 ...)
                      (if test
                          (begin stmt1
                                 stmt2 ...))))))
  (let ((if \schtrue))
    (when if (set! if 'now))
    if))                           \ev  now

(let ((x 'outer))
  (let-syntax ((m (syntax-rules () ((m) x))))
    (let ((x 'inner))
      (m))))                       \ev  outer%
\end{scheme}

\end{entry}

\begin{entry}{%
\proto{letrec-syntax}{ \hyper{bindings} \hyper{body}}{\exprtype}}

\syntax
Same as for {\cf let-syntax}.

\semantics
 The \hyper{body} is expanded in the syntactic environment obtained by
extending the syntactic environment of the {\cf letrec-syntax}
expression with macros whose keywords are the
\hyper{keyword}s, bound to the specified transformers.
Each binding of a \hyper{keyword} has the \hyper{bindings}
as well as the \hyper{body} within its region,
so the transformers can
transcribe expressions into uses of the macros
introduced by the {\cf letrec-syntax} expression.

\begin{scheme}
(letrec-syntax
  ((my-or (syntax-rules ()
            ((my-or) \schfalse)
            ((my-or e) e)
            ((my-or e1 e2 ...)
             (let ((temp e1))
               (if temp
                   temp
                   (my-or e2 ...)))))))
  (let ((x \schfalse)
        (y 7)
        (temp 8)
        (let odd?)
        (if even?))
    (my-or x
           (let temp)
           (if y)
           y)))        \ev  7%
\end{scheme}

\end{entry}

\subsection{Pattern language}
\label{patternlanguage}

A \hyper{transformer spec} has the following form:

\begin{entry}{%
\proto{syntax-rules}{ \hyper{literals} \hyper{syntax rule} \dotsfoo}{}}

\syntax
\hyper{Literals} is a list of identifiers and each \hyper{syntax rule}
should be of the form
\begin{scheme}
(\hyper{pattern} \hyper{template})%
\end{scheme}
The \hyper{pattern} in a \hyper{syntax rule} is a list \hyper{pattern}
that begins with the keyword for the macro.

A \hyper{pattern} is either an identifier, a constant, or one of the
following
\begin{scheme}
(\hyper{pattern} \ldots)
(\hyper{pattern} \hyper{pattern} \ldots . \hyper{pattern})
(\hyper{pattern} \ldots \hyper{pattern} \hyper{ellipsis})
\#(\hyper{pattern} \ldots)
\#(\hyper{pattern} \ldots \hyper{pattern} \hyper{ellipsis})%
\end{scheme}
and a template is either an identifier, a constant, or one of the following
\begin{scheme}
(\hyper{element} \ldots)
(\hyper{element} \hyper{element} \ldots . \hyper{template})
\#(\hyper{element} \ldots)%
\end{scheme}
where an \hyper{element} is a \hyper{template} optionally
followed by an \hyper{ellipsis} and
an \hyper{ellipsis} is the identifier ``{\cf ...}'' (which cannot be used as
an identifier in either a template or a pattern).\schindex{...}

\semantics An instance of {\cf syntax-rules} produces a new macro
transformer by specifying a sequence of hygienic rewrite rules.  A use
of a macro whose keyword is associated with a transformer specified by
{\cf syntax-rules} is matched against the patterns contained in the
\hyper{syntax rule}s, beginning with the leftmost \hyper{syntax rule}.
When a match is found, the macro use is transcribed hygienically
according to the template.

An identifier that appears in the pattern of a \hyper{syntax rule} is
a {\em pattern variable}, unless it is the keyword that begins the pattern,
is listed in \hyper{literals}, or is the identifier ``{\cf ...}''.
Pattern variables match arbitrary input elements and
are used to refer to elements of the input in the template.  It is an
error for the same pattern variable to appear more than once in a
\hyper{pattern}.

The keyword at the beginning of the pattern in a
\hyper{syntax rule} is not involved in the matching and
is not considered a pattern variable or literal identifier.

\begin{rationale}
The scope of the keyword is determined by the expression or syntax
definition that binds it to the associated macro transformer.
If the keyword were a pattern variable or literal
identifier, then
the template that follows the pattern would be within its scope
regardless of whether the keyword were bound by {\cf let-syntax}
or by {\cf letrec-syntax}.
\end{rationale}

Identifiers that appear in \hyper{literals} are interpreted as literal
identifiers to be matched against corresponding subforms of the input.
A subform
in the input matches a literal identifier if and only if it is an
identifier
and either both its occurrence in the macro expression and its
occurrence in the macro definition have the same lexical binding, or
the two identifiers are equal and both have no lexical binding.

% [Bill Rozas suggested the term "noise word" for these literal
% identifiers, but in their most interesting uses, such as a setf
% macro, they aren't noise words at all. -- Will]

A subpattern followed by {\cf ...} can match zero or more elements of the
input.  It is an error for {\cf ...} to appear in \hyper{literals}.
Within a pattern the identifier {\cf ...} must follow the last element of
a nonempty sequence of subpatterns.

More formally, an input form $F$ matches a pattern $P$ if and only if:

\begin{itemize}
\item $P$ is a non-literal identifier; or

\item $P$ is a literal identifier and $F$ is an identifier with the same
      binding; or

\item $P$ is a list {\cf ($P_1$ $\dots$ $P_n$)} and $F$ is a
      list of $n$
      forms that match $P_1$ through $P_n$, respectively; or

\item $P$ is an improper list
      {\cf ($P_1$ $P_2$ $\dots$ $P_n$ . $P_{n+1}$)}
      and $F$ is a list or
      improper list of $n$ or more forms that match $P_1$ through $P_n$,
      respectively, and whose $n$th ``cdr'' matches $P_{n+1}$; or

\item $P$ is of the form
      {\cf ($P_1$ $\dots$ $P_n$ $P_{n+1}$ \meta{ellipsis})}
      where \meta{ellipsis} is the identifier {\cf ...}
      and $F$ is
      a proper list of at least $n$ forms, the first $n$ of which match
      $P_1$ through $P_n$, respectively, and each remaining element of $F$
      matches $P_{n+1}$; or

\item $P$ is a vector of the form {\cf \#($P_1$ $\dots$ $P_n$)}
      and $F$ is a vector
      of $n$ forms that match $P_1$ through $P_n$; or

\item $P$ is of the form
      {\cf \#($P_1$ $\dots$ $P_n$ $P_{n+1}$ \meta{ellipsis})}
      where \meta{ellipsis} is the identifier {\cf ...}
      and $F$ is a vector of $n$
      or more forms the first $n$ of which match
      $P_1$ through $P_n$, respectively, and each remaining element of $F$
      matches $P_{n+1}$; or

\item $P$ is a datum and $F$ is equal to $P$ in the sense of
      the {\cf equal?} procedure.
\end{itemize}

It is an error to use a macro keyword, within the scope of its
binding, in an expression that does not match any of the patterns.

When a macro use is transcribed according to the template of the
matching \hyper{syntax rule}, pattern variables that occur in the
template are replaced by the subforms they match in the input.
Pattern variables that occur in subpatterns followed by one or more
instances of the identifier
{\cf ...} are allowed only in subtemplates that are
followed by as many instances of {\cf ...}.
They are replaced in the
output by all of the subforms they match in the input, distributed as
indicated.  It is an error if the output cannot be built up as
specified.

%%% This description of output construction is very vague.  It should
%%% probably be formalized, but that is not easy...

Identifiers that appear in the template but are not pattern variables
or the identifier
{\cf ...} are inserted into the output as literal identifiers.  If a
literal identifier is inserted as a free identifier then it refers to the
binding of that identifier within whose scope the instance of
{\cf syntax-rules} appears.
If a literal identifier is inserted as a bound identifier then it is
in effect renamed to prevent inadvertent captures of free identifiers.

As an example, if \ide{let} and \ide{cond} are defined as in
section~\ref{derivedsection} then they are hygienic (as required) and
the following is not an error.

\begin{scheme}
(let ((=> \schfalse))
  (cond (\schtrue => 'ok)))           \ev ok%
\end{scheme}

The macro transformer for {\cf cond} recognizes {\cf =>}
as a local variable, and hence an expression, and not as the
top-level identifier {\cf =>}, which the macro transformer treats
as a syntactic keyword.  Thus the example expands into

\begin{scheme}
(let ((=> \schfalse))
  (if \schtrue (begin => 'ok)))%
\end{scheme}

instead of

\begin{scheme}
(let ((=> \schfalse))
  (let ((temp \schtrue))
    (if temp ('ok temp))))%
\end{scheme}

which would result in an invalid procedure call.

\end{entry}


\documentclass[11 pt]{scrartcl}
\usepackage[header, margin, koma]{tyler}

\newcommand{\hwtitle}{LLN and the Central Limit Theorem}

\pagestyle{fancy}
\fancyhf{}
\fancyhead[l]{\hwtitle{}}
\fancyhead[r]{Tyler Zhu}
\cfoot{\thepage}

\begin{document}
\title{\Large \hwtitle{}}
\author{\large Tyler Zhu}
\date{\large\today}

\maketitle

The idea of this worksheet is to get you to the point where applying the Central Limit Theorem becomes natural and doesn't require memorizing a formula to apply it. If you actually try solving each problem on its own, this should do its job.

\section{Warm-Up: Law of Large Numbers}

\begin{problem}
    This problem will walk you through a proof of the Law of Large Numbers. The setup is as follows: we have $n$ i.i.d. random variables $X_1, \dots, X_n$ where $\EE[X_i] = \mu$ and $\Var(X_i) = \si^2$. Our intuition tells us that in the long run, we'd expect the average of these random variables to approach the true underlying mean.
    \alphanum
        \ii Create an unbiased estimator $M_n$ for the mean $\mu$.
        \ii What are $\EE[M_n]$ and $\Var(M_n)$?
        \ii Suppose I used Chebyshev's inequality to create a confidence interval $[\mu-\eps, \mu+\eps]$ for $M_n$. As $n\to\infty$, how confident am I that $M_n$ will be in this interval? How does this relate to the law of large numbers?
    \enumend
\end{problem}

So LLN tells us that their average will eventually be very close to the mean, but it doesn't tell me how confident I can be for a particular $n$. That's where CLT comes in.

\section{Central Limit Theorem}
First we'll see how we can derive the Central Limit Theorem to gain intuition for why it works, then I'll present it.

\begin{problem}
    Your friend comes up to you and tells you about the new BLT theorem, which says that the sum of $n$ i.i.d. random variables is approximately Gaussian for large $n$, but forgot what the parameters of it looks like. It's your job to figure out exactly what they should be. Similar to the last problem, suppose that $X_1, \dots, X_n$ are i.i.d. where $\EE[X_i] = \mu$ and $\Var(X_i) = \si^2$.
    \alphanum
        \ii Let $S_n = X_1 + \dots + X_n$. What are $\EE[S_n]$ and $\Var(S_n)$?
        \ii Define a new r.v. $Z_n$ in terms of $S_n$ which has mean 0 and standard deviation 1.
        \ii The \emph{z-score} of a data point is how many standard deviations (+/-) it's away from the mean. Given some observation $x$ in the distribution $S_n$, what would it's z-score be?
        \ii Your friend's BLT theorem tells you that $Z_n\sim \Nor(0,1)$, i.e. it's approximately a standard normal Gaussian, in the following sense:
        \[ \lim_{n\to\infty} \PP[Z_n \leq z] = \Phi(z)\]
        where $\Phi(z)$ is the CDF of the standard normal Gaussian. Given this, what is $\PP[S_n \leq x]$ for some $x$?
    \enumend
\end{problem}

Here's the general theorem for reference.
\begin{theorem}[Central Limit Theorem]
    Let $X_1, \dots, X_n$ be i.i.d. r.v.'s where $\EE[X_i] = \mu$ and $\Var(X_i) = \si^2$, and define $S_n = X_1 + \dots + X_n$. Then as $n\to\infty$, the CDF of $S_n$ approaches that of the CDF of a $\Nor(n\mu, n\si^2)$ distribution. In terms of z-scores, if $Z_n = \frac{S_n-n\mu}{\si\sqrt{n}}$, then
    \[ \lim_{n\to\infty} \PP[Z_n \leq z] = \Phi(z)\]
    where $\Phi(z)$ is the CDF of a standard normal Gaussian.
\end{theorem}

\section{Past Practice Problems}

\begin{problem}[Sp19 Final \#7]
    Suppose the number of people that walk into Jonathan's favorite McDonald's in an hour is $\sim\Poisson(\la)$, where $\la$ is unknown but is definitely at most 10. How many hours does Jonathan need to be at McDonalds to be able to construct a 95\% confidence interval for $\la$ that is of width 2?
\end{problem}

\begin{problem}[Fa19 Final \#8]
    Let $X_i\sim \Poisson(1)$ be independent r.v.'s and $S_n = X_1 + \dots + X_n$ be their sum, and let $c,\eps$ be some constants. For $\eps < \frac 12$, what is $\lim_{n\to\infty}\PP[S_n < cn^\eps+n]$?
\end{problem}

\end{document}


% $Id$
% Copyright 2009-2013 CV Radhakrishnan.
% Released under LPPLv1.3+.
%
% TeX4ht and MathML 3.

\ifx\texhtstandalonedoc1
\documentclass[a4paper]{article}
\usepackage{xspace,blog}
\begin{document}
\section{MathML 3 and implications on TeX4ht}
\else
\chapter{MathML 3 and implications for \TeX4ht}
\fi

\leavevmode \hlink{http://www.w3.org/TR/MathML3/}{\mathml 3} is about to
be formalized and going to be released as the new standard for encoding
mathematics in web. It differs from the previous standard version 2. The
main changes that have a bearing on the functionality of
\hlink{http://www.tug.org/tex4ht/}{\texht} are discussed here.

\section{Linking}

\mathml 1 and 2 didn't have any built in provisions to specify links for
various elements. The recommendation was to use
\hlink{http://www.w3.org/TR/xlink/}{\xlink} since it was part of the
original grand plan for \hlink{http://www.w3.org/standards/xml/}{\xml}
in its formative years. However, \xlink didn't gain much popularity nor
was it supported widely. Therefore, \mathml 3 now specifies that any
\mathml element can accept an \verb+href+ attribute that takes an \uri
specifying a hyperlink same as in the
\hlink{http://dev.w3.org/html5/spec/Overview.html}{\html} element,
namely, \verb+<a>+. So this has an implication in the current scheme of
\texht. If readers provide a few examples of how they want to include
links in a math fragment in \latex, it will help largely to make a
stable and suitable conversion scheme for \texht.

\section{Line breaking}

Previous standards of \mathml had the same limitations as \tex in the
matter of breaking long equations. In \tex, it is easy for an author to
break equations while authoring content taking into consideration of the
margin constrains and paper sizes. However, for web content, margin and
line-length are irrelevant when the window sizes are unknown or
potentially liable to dynamic changes. Therefore, new \mathml 3
specifies a line breaking model and introduces several new attributes to
control properties of line breaks and alignments.

This has deeper implications on the rendering software than on the
engine that creates \mathml.  However, since the specification allows
newer properties for line breaks and alignments, we need to take care of
those part in \texht which at the moments obeys what the author has
input in her \latex document.  Since \tex is incapable of determining
the semantic meaning of equations, we have to provide hooks to make
\texht aware of the real line breaks and obligatory line breaks to
adjust with page sizes.  A better option will be to make use of
\verb+breqn+ package while authoring and \texht to provide necessary
extra functionality to take care of
\hlink{http://ctan.org/pkg/breqn}{\texttt{breqn}}
features in combination with \mathml's newer goodies.

\section{Image inclusion}

The usage of \verb+<glyph>+ element in the previous \mathml
specification has been deprecated now. \verb+<glyph>+ element was used
to specify characters from non-standard fonts that do not correspond to
Unicode code points. Since the usage becomes difficult in a web context,
as one needs to make sure that the font is available, \verb+<mglyph>+
has been extended with \verb+src+ attribute. \verb+<mglyph>+ now acts as
a general image reference element in \mathml much like \html's
\verb+<img>+ element.

\section{Elementary math layout}

Elementary school math layout is difficult to typeset even with \tex.
Usually people adopt a tabular layout with a lot of complex macros to
control space and rules around various number segments. Previous \mathml
standards provide elementary school math layout, much like in \tex, with
a lot of tabular structure which obstructs rendering of math other than
visual, particularly audio, because of the interference of tabular
elements.  \mathml 3 provides better layout elements and scheme which
help to specify even borrows and carries and many different kind of
layout.

\begin{verbatim}
  435.3
   ______
  3)1306
    12
    __
     10
      9
     __
      16
      15
      __
       1.0
         9
         _
         1
\end{verbatim}

\subsection{MathML version of long division}

Given below is the \mathml 3 coding of the above long division.

\begin{verbatim}
<mlongdiv longdivstyle="lefttop">
  <mn> 3 </mn>
  <mn> 435.3</mn>
  <mn> 1306</mn>
  <msgroup position="2" shift="-1">
    <msgroup>
      <mn> 12</mn>
      <msline length="2"/>
    </msgroup>
    <msgroup>
      <mn> 10</mn>
      <mn> 9</mn>
      <msline length="2"/>
    </msgroup>
    <msgroup>
      <mn> 16</mn>
      <mn> 15</mn>
      <msline length="2"/>
      <mn> 1.0</mn>
    </msgroup>
    <msgroup position='-1'>
       <mn> 9</mn>
      <msline length="3"/>
      <mn> 1</mn>
    </msgroup>
  </msgroup>
</mlongdiv>
\end{verbatim}

\section{Directionality}

\ifvmode\leavevmode\fi
\mathml 3 provides support for right to left writing/reading direction
whereas previous versions didn't have this functionality. The new
specifications provide the user to control both writing directions of
the identifiers within a formula and layout direction of the formula
itself separately. I am not sure, if this has any influence on the
behavior of current version of \texht which is based on \verb+dvi+ files
generated by \tex/\latex while support for \verb+xdv+, extended dvi
generated by Xe\tex, is still very basic which supports
multi-directional scripts.

\ifx\texhtstandalonedoc1 \end{document}\fi


\documentclass[epsfig,10pt,fullpage]{article}

\newcommand{\LabNum}{3}
\newcommand{\CommonDocsPath}{../../../common/docs}
\input{\CommonDocsPath/preamble.tex}

\begin{document}

\centerline{\huge Digital Logic}
~\\
\centerline{\huge Laboratory Exercise \LabNum}
~\\
\centerline{\large Latches, Flip-flops, and Registers}
~\\

\noindent
The purpose of this exercise is to investigate latches, flip-flops, and registers.

\section*{Part I}
\addcontentsline{toc}{1}{Part I}
Intel\textsuperscript{\textregistered} FPGAs include flip-flops that are available for implementing a user's circuit.
We will show how to make use of these flip-flops in Part IV of this exercise. But
first we will show how storage elements can be created in an FPGA without using
its dedicated flip-flops.

Figure~\ref{fig:RSlatch} depicts a gated RS latch circuit. A style of VHDL code that
uses logic expressions to describe this circuit is given in Figure~\ref{fig:latch_code}.
If this latch is implemented in an FPGA that has 4-input lookup tables (LUTs),
then only one lookup table is needed, as shown in Figure~\ref{fig:RSlatch_cct}$a$.

\begin{figure}[H]
	\begin{center}
		\includegraphics[scale=.9]{figures/RS_latch.pdf}
	\end{center}
\caption{A gated RS latch circuit.}
\label{fig:RSlatch}
\end{figure}

\begin{figure}[H]
\begin{center}
\begin{minipage}[t]{12.5 cm}
\begin{tabbing}
-\,- A gated RS latch desribed the hard way\\
LIBRARY ieee;\\
USE ieee.std\_logic\_1164.all;\\
\\
ZZ\=PORT ~( \=Clk, R, S	\=: OUTZZ\=STD\_LOGIC;\kill
ENTITY part1 IS\\
\>PORT (\>Clk, R, S \>: IN	\>STD\_LOGIC;\\
\>\>Q \>: OUT \>STD\_LOGIC);\\
END part1;\\
\\
ARCHITECTURE Structural OF part1 IS\\
\>SIGNAL R\_g, S\_g, Qa, Qb : STD\_LOGIC ;\\
\>ATTRIBUTE KEEP : BOOLEAN;\\
\>ATTRIBUTE KEEP OF R\_g, S\_g, Qa, Qb : SIGNAL IS TRUE;\\
BEGIN	\\
\>R\_g $<$= R AND Clk;\\
\>S\_g $<$= S AND Clk;\\
\>Qa $<$= NOT (R\_g OR Qb);\\
\>Qb $<$= NOT (S\_g OR Qa);\\
~\\
\>Q $<$= Qa;\\
~\\
END Structural;
\end{tabbing}
\end{minipage}
\end{center}
\caption{Specifying the RS latch by using logic expressions.}
\label{fig:latch_code}
\end{figure}

Although the latch can be correctly realized in one 4-input LUT, this implementation
does not allow its internal signals, such as $R\_g$ and $S\_g$, to be observed, because
they are not provided as outputs from the LUT. To preserve these internal signals in
the implemented circuit, it is necessary to include a {\it compiler
directive} in the code.  In Figure~\ref{fig:latch_code} the directive KEEP is
included by using a VHDL ATTRIBUTE statement to instruct the Quartus\textsuperscript{\textregistered} compiler to use separate logic elements for each of
the signals $R\_g, S\_g, Qa,$ and $Qb$. Compiling the code produces the circuit with four
4-LUTs depicted in Figure~\ref{fig:RSlatch_cct}$b$.

\begin{figure}[H]
	\begin{center}
		\includegraphics[scale=0.9]{figures/figure3.pdf}
	\end{center}
	\caption{Implementation of the RS latch from Figure~\ref{fig:RSlatch}.}
\label{fig:RSlatch_cct}
\end{figure}

Create a Quartus project for the RS latch circuit as follows:
\begin{enumerate}
\item Create a new Quartus project for your DE-series board.
\item Generate a VHDL file with the code in Figure~\ref{fig:latch_code}
and include it in the project.
\item Compile the code. Use the Quartus RTL Viewer tool to examine the gate-level
circuit produced from the code, and use the Technology Map Viewer tool
to verify that the latch is implemented as shown in Figure~\ref{fig:RSlatch_cct}$b$.

\item Simulate the behavior of your VHDL code by using the simulation feature provided
in the Modelsim software. Use the testbench provided in the laboratory materials to drive
the signals for your simulation. The procedure for using Modelsim for simulation is
described in the tutorial {\it Using the ModelSim-Intel FPGA Simulator}. An example of a
vector waveform file is displayed in Figure~\ref{fig:sim}. The waveforms in the figure
begin by setting {\it Clk} $= 1$ and $R = 1$, which allows the simulation tool to
initialize all of the signals inside of the latch to known values.
\end{enumerate}

\begin{figure}[H]
	\begin{center}
		\includegraphics[width = 5in]{figures/simulation.pdf}
	\end{center}
	\caption{Simulation waveforms for the RS latch.}
\label{fig:sim}
\end{figure}

\section*{Part II}
\addcontentsline{toc}{2}{Part II}
Figure~\ref{fig:gatedD} shows the circuit for a gated D latch.

\begin{figure}[H]
	\begin{center}
		\includegraphics[]{figures/D_latch.pdf}
	\end{center}
	\caption{Circuit for a gated D latch.}
\label{fig:gatedD}
\end{figure}

Perform the following steps:

\begin{enumerate}
\item Create a new Quartus project. Generate a VHDL file using the style of code
in Figure~\ref{fig:latch_code} for the gated D latch. Use the KEEP directive to ensure
that separate logic elements are used to implement the signals $R, S\_g, R\_g, Qa,$ and
$Qb$.
\item Compile your project and then use the
Technology Map Viewer tool to examine the implemented circuit.
\item Verify that the latch works properly for all input conditions by using functional
simulation. Examine the timing characteristics of the circuit by using timing simulation.
\item Create a new Quartus project which will be used for implementation of the gated D
latch on your DE-series board. This project should consist of a top-level module that
contains the appropriate input and output ports (pins) for your board. Instantiate your
latch in this top-level module. Use switch {\it SW}$_0$ to drive the {\it D} input of the latch,
and use {\it SW}$_1$ as the {\it Clk} input. Connect the Q output to {\it LEDR}$_{0}$.
\item
Include the required pin assignments and then compile your project and download the
compiled circuit onto your DE-series board.
\item
Test the functionality of your circuit by toggling the $D$ and {\it Clk} switches and observing
the Q output.
\end{enumerate}

\section*{Part III}
\addcontentsline{toc}{3}{Part III}
Figure~\ref{fig:MS_FF} shows the circuit for a master-slave D flip-flop.

\begin{figure}[H]
	\begin{center}
		\includegraphics[]{figures/figure5.pdf}
	\end{center}
	\caption{Circuit for a master-slave D flip-flop.}
\label{fig:MS_FF}
\end{figure}

Perform the following:
\begin{enumerate}
\item Create a new Quartus project. Generate a VHDL file that instantiates two
copies of your gated D latch module from Part II to implement the master-slave flip-flop.
\item Include in your project the appropriate input and output ports for your
DE-series board. Use switch {\it SW}$_0$ to drive the D input of the flip-flop,
and use {\it SW}$_1$ as the {\it Clock} input. Connect the Q output to {\it LEDR}$_{0}$.
\item
Include the required pin assignments and then compile your project.
\item Use the Technology Viewer to examine the D flip-flop circuit, and use
simulation to verify its correct operation.
\item
Download the circuit onto your DE-series board and test its functionality
by toggling the $D$ and {\it Clock} switches and observing the Q output.
\end{enumerate}

\newpage
\section*{Part IV}
\addcontentsline{toc}{4}{Part IV}
Figure~\ref{fig:waves} shows a circuit with three different storage elements: a gated D latch,
a positive-edge triggered D flip-flop, and a negative-edge triggered D flip-flop.

\begin{figure}[H]
	\begin{center}
		\includegraphics[]{figures/figure6.pdf}
	\end{center}
	\caption{Circuit and waveforms for Part IV.}
\label{fig:waves}
\end{figure}

Implement and simulate this circuit using the Quartus software as follows:
\begin{enumerate}
\item Create a new Quartus project.
\item Write a VHDL file that instantiates the three storage elements. For this part you
should no longer use the KEEP directive (that is, the VHDL ATTRIBUTE statement) from Parts I
to III. Figure~\ref{fig:behave} gives a behavioral style
of VHDL code that specifies the gated D latch in Figure~\ref{fig:gatedD}.
This latch can be implemented in one 4-input lookup table. Use a similar style of
code to specify the flip-flops in Figure~\ref{fig:waves}.
\item Compile your code and use the Technology Map Viewer to examine the implemented circuit.
Verify that the latch uses one lookup table and that the flip-flops are implemented using
the flip-flops provided in the target FPGA.
\item Use Modelsim to simulate the circuit you created. Use the included testbench file to
specify the inputs $D$ and {\it Clock} as indicated in Figure~\ref{fig:waves}.
Make sure that the testbench correctly instantiates the module you created and
run the simulation to observe the different behavior of the three storage elements.
\end{enumerate}

\begin{figure}[H]
\begin{center}
\begin{minipage}[t]{12.5 cm}
\begin{tabbing}
LIBRARY ieee ; \\
USE ieee.std\_logic\_1164.all ; \\
~\\
ENTITY latch IS \\
ZZ\=PORT ~( \=D,ClkZ \=: OUTZ\=STD\_LOGIC;\kill
\>PORT (	\>D, Clk \>: IN \>STD\_LOGIC ; \\
\>\>Q \>: OUT \>STD\_LOGIC) ; \\
END latch ;\\
~\\
ARCHITECTURE Behavior OF latch IS    \\
BEGIN\\
ZZ\=ZZ\=ZZ\=ZZ\=\kill
\>PROCESS ( D, Clk ) \\
\>BEGIN\\
\>\>IF Clk = '1' THEN \\
\>\>\>Q $<$= D ; \\
\>\>END IF ; \\
\>END PROCESS ; \\
END Behavior ;\\
\end{tabbing}
\end{minipage}
\end{center}
\caption{A behavioral style of VHDL code that specifies a gated D latch.}
\label{fig:behave}
\end{figure}

\section*{Part V}
\addcontentsline{toc}{5}{Part V}
We wish to display the hexadecimal value of an 8-bit number $A$
on the two 7-segment displays $HEX3-2$.  We also wish to display the
hex value of an 8-bit number $B$ on the two 7-segment displays $HEX1-0$.
The values of $A$ and $B$ are inputs to the circuit which are
provided by means of switches $SW_{7-0}$.  To input the values of $A$ and $B$,
first set the switches to the desired value of $A$, store these switch values in a register,
and then change the switches to the desired value of $B$.  Finally, use an adder to
generate the arithmetic sum $S = A + B$, and display this sum on the 7-segment
displays $HEX5-4$. Show the carry-out produced by the adder on LEDR(0).
\begin{enumerate}
\item Create a new Quartus project which will be used to implement the desired
circuit on your DE-series board.
\item Write a VHDL file that provides the necessary functionality. Use {\it KEY}$_0$ as
an active-low asynchronous reset, and use {\it KEY}$_1$ as a clock input.
\item Include the necessary pin assignments for the pushbutton switches and 7-segment
displays, and then compile the circuit.
\item Download the circuit onto your DE-series board and test its functionality
by toggling the switches and observing the output displays.
\end{enumerate}

\input{\CommonDocsPath/copyright.tex}
\end{document}