% -*- mode: latex; -*- mustache tags:  
\ifx\wholebook\relax\else

	\documentclass[10pt,twoside,english]{root/support/latex/sbabook/sbabook}
  \usepackage{import}
  \subimport{root/support/latex/}{common.tex}

  \hypersetup{pdfinfo = {
    Title = {{Pharo Mooc}},
    Author = {},
    Keywords = {pharo, smalltalk}}}
  \begin{document}
\fi

\chapter{Rewriting Expressions - Solution}
In this exercise we ask you to rewrite some expressions or to understand the different forms that a solution can take. Some of the expressions are explained in \url{https://medium.com/concerning-pharo/elegant-pharo-code-bb590f0856d0}
\subsection{Exercise: Examine the block expressions}
\begin{displaycode}{smalltalk}
	| sum |
	sum := 0.
	#(21 23 53 66 87) do: [:item | sum := sum + item].
	sum
\end{displaycode}
\subsubsection{Exercise:}
\begin{itemize}
\item What is the final result of sum?
\end{itemize}

\textbf{Solution.}
The sum of all the numbers of the array: 250
\subsubsection{Exercise:}
\begin{itemize}
\item Rewrite this piece of code to use explicit array indexing (with the message \textcode{at:}) to access the array elements. Test your version. 
\end{itemize}

\textbf{Solution.}

\begin{displaycode}{smalltalk}
	| array sum |
	array := #(21 23 53 66 87).
	sum := 0.
	1 to: array size do: [ :i | sum := sum + array at: i ].
	sum
\end{displaycode}
\subsubsection{Exercise:}
\begin{itemize}
\item Rewrite this code using \textcode{inject:into:} (check the implementation of \textcode{inject:into:} and its users in the system to understand how to use it).
\end{itemize}

\textbf{Solution.}

\begin{displaycode}{smalltalk}
#(21 23 53 66 87) inject: 0 into: [:item :sum | sum + item]
\end{displaycode}
\subsection{Exercise: Comparing expressions}
You can express in different way the same computation. Have a look at each of them and check the messages that you do not know. Look for their implementation. 

\begin{displaycode}{smalltalk}
| array |
array := #(2 4 4 4 5 5 7 9).
((array - array average) squared sum / (array size - 1)) sqrt 
\end{displaycode}

\begin{displaycode}{smalltalk}
[ :input | ((input - input average) squared sum / (input size - 1)) sqrt ] 
    value: #(2 4 4 4 5 5 7 9) 
\end{displaycode}

\begin{displaycode}{smalltalk}
#(2 4 4 4 5 5 7 9) in: [ :input |
    ((input - input average) squared sum / (input size - 1)) sqrt ]
\end{displaycode}

\begin{displaycode}{smalltalk}
#(2 4 4 4 5 5 7 9) stddev
\end{displaycode}


\ifx\wholebook\relax\else
\end{document}
\fi