\input{../settings/settings}
\usepackage{amssymb}
\usepackage[caption=false,font=footnotesize]{subfig}

\begin{document}
\klausur{Nichtprozedurale Programmierung}{Prof. M. Mendler}{Wintersemester 15/16}{90}{Wörterbuch}
\begin{enumerate}
\item{Recall the state monad type constructor
	
	\begin{verbatim}
	data State s b = State (s -> (s, b))
	\end{verbatim}

which captures polymorphic state transformations over states of type s returning a result of type b. Values are of the form \texttt{State act :: State s b} where \texttt{act} is an action function that takes a state \texttt{current :: s} and produces a pair \texttt{act current = (next, out)} consisting of a new state \texttt{next :: s} and an output value \texttt{out :: b}. The function to execute a state transformation is called runState:

	\begin{verbatim}
		runState :: s -> State s b -> (s, b)
		runState current (State act) = act current
	\end{verbatim}

The type constructor \texttt{State s} is an instance of monad through the following instance declaration:

	\begin{verbatim}
		instance Monad (State s) where
			return :: b -> State s b
			return v = State (\\st -> (st, v))
			(>>=) :: State s b -> (b -> State s c) -> State s c
			step >>= mkstep =
				State (\\oldst -> let (newst, res)) = runState oldst step
					in runState newst (mkstep res)
	\end{verbatim}

defining the polymorphic monad methods return and \texttt{(>>=)}. These can be used generically for every instance of State s b either directly or via the 'do' notation of the monad.

Your task is to use the state monad to program the state machine of a simple lock controller for a hotel safe as you may find in a hotel room for guests to keep their valuables.
The hotel safe has a keypad with for digiits \texttt{D0, D1, D2, D3} to define and enter a secret access code as well as an Enter and a Reset key. Normally, when a new guest arrives, the door of the safe is open. The guest can enter an arbitrary sequence of digits and complete by pressing the Enter key. The sequence of digits entered is taken and memorised as the secret user access code. The safe is now Locked so that when the door is closed the safe can only be opened by entering the identical user access code followed by Enter. If the code is good then the locking mechannism releases and the lock is Open. If the code is wrong the safe remains Closed. For simplicity we assume that there is no limit on the number of attempts to open the lock. At any moment, whatever the user key and whether the lock is open or closed, the Reset key be pressed. This makes the lock Closed and activates the secret master key \texttt{[D3, D1, D3, D1]}, which we assume is only known to the hotel. The guest will have to ask the reception desk for help to reopen the safe in case they press Reset with the door closed.

The interface of the lock controller is captured by the following data types:

	\begin{verbatim}
		data Lock = Open | Closed
		data Digit = D0 | D1 | D2 | D3
		data Action = Press Digit | Enter | Reset
	\end{verbatim}

The type Lock represents the state of the lock. The type \texttt{Digit} is the representation of the four digits Action is the data type of possible user actions: The user can press a particular digit key, press the Enter key to complete inputting a code or press Reset to reset the controller.

Your program as requested in the sub-questions (a), (b) and (c) below must implement at least the following behaviour:

\begin{itemize}
	\item Suppose the lock is open and after an arbitrary non-zero number of Press d actions the action Enter is executed. Then the sequence of digits entered is registered as the new (temporary) user key and the lock is closed.
	
	\item Suppose the lock is closed and after an arbitrary non-zero number of Press d actions the action Enter is executed. Then, if a user key has been set before and the entered sequence of digits matches this user key, the lock is opened.
	
	\item Pressing Enter without prior Press d actions has no effect.
	
	\item The Reset action always closes the lock and activates the master key squence \texttt{[D3, D1, D3, D1]} in place of the user key.
\end{itemize}

\begin{enumerate}
	\item First define (i) a suitable data type \texttt{CntrState} for the internal state of the control mechanism, (ii) an intital state \texttt{initState :: CntrlState -> Lock} which extracts (accesses) the state of the lock from (in) the full state of the controller.
	Make sure your data structure for \texttt{CntrState} contains enough information to implement the correct state change of the lock as descibed in the above informal specification. In the state \texttt{initState} the lock must be open, i.e., \texttt{lock initState == Open}.
	
	Explain your workings! Specifically, explain your choice of the type \texttt{CntrlState} and how it stores the information necessary to control the lock.
	
	\item Next construct a Haskell function
	\begin{verbatim}
		execute :: Action -> State CntrlState ()
	\end{verbatim}
	which translates each action into an appropriate state transformation over the type \texttt{CntrlState} of control states defined in the previous question part.
	
	\item Finally, construct a function
	\begin{verbatim}
		compile :: [Action] -> State CntrlState ()
	\end{verbatim}
	which executes a sequence of actions using the function \texttt{execute} from the previous question part. The result of \texttt{compile actions} must code the overall state transformation effected by a sequence \texttt{actions :: [Action]} from an arbitrary start state. Your program for compile must use the monad method (\texttt{>>=}) or the 'do' notation to accumulate the state transformations of the monad type \texttt{'State CntrlState'}.
	
	Examples:
	
	\begin{verbatim}
	lock $ fst $ runState initState $
		compile []
	==> Open -- in the inital state the lock is open
	
	lock $ fst $ runState initState $
		compile [Press D1, Press D2, Press D3, Enter]
	==> Closed -- the first user key is entered, lock is closed
	
	lock $ fst $ runState initState $
		compile [Press D1, Press D2, Press D3, Enter, Press D0, Press D0, Enter]
	
	==> Closed -- new user key entered, then attempt to open with wrong key, 
			   -- safe remains locked
			   
	lock $ fst $ runState initState $
		compile [Press D0, Press D0, Enter, Press D0, Press D0, Enter]
	==> Open -- set new user key, opened with correct user key
	
	lock $ fst $ runState initState $
		compile [Press D1, Press D2, Press D3, Enter, Press D0, Press D0, Enter, Reset,
		 	Press D3, Press D1, Press D3, Press D1, Enter]
	==> Open -- set user key, failed attempt to open with wrong key, 
	         -- then reset, finally opened with master key
	\end{verbatim}
\end{enumerate}
}\item Recall the ''Kahn'' dataflow network seen \textbf{on the left} of \autoref{img:fig1}.
The network is defined by a recursive system of stream definitions as follows:
	\begin{verbatim}
	xs, ys0, ys1, ts0, ts1 :: Str Int
	xs = kf ys0 ys1
	ys0 = kh0 ts0
	ys1 = kh1 ts1
	(ts0, ts1) = kg xs
	\end{verbatim}
Assume that the nodes \texttt{kh0} and \texttt{kh1} are implemented like this:
	\begin{verbatim}
	kh0 :: Str Int -> Str Int
	kh0 (t0 : ts0) = (t0 + 1) : (t0 + 2) : kh0 ts0

	kh1 :: Str Int -> Str Int
	kh1 ts1 = 1 : kh1' ts1
	  where kh1' (t0 : t1 : ts1) = (t0 + t1) : kh1' ts1
	\end{verbatim}
In the following two question parts you are asked to discuss two types of implementations for the two other nodes \texttt{kf} and \texttt{kg}.
\begin{enumerate}
	\item For the first question part suppose that the stream processing functions \texttt{kf} and \texttt{kg} of ''Kahn'' (\autoref{img:fig1} left) are defined such that
	\begin{verbatim}
	kf :: Str Int -> Str Int -> Str Int
	kf ys0 (y1 : ys1) = y1 : kf' ys0 ys1
	  where kf' (y0 : y0' : ys0) ys1 = y0 : y0' : kf ys0 ys1

	kg :: Str Int -> (Str Int, Str Int)
	kg xs = (get1 xs, skip1 xs)
	  where get1 (x : xs) = x: skip2 xs
		get2 (x1 : x2 : xs) = x1 : x2 : skip1 xs
		skip2 (_ : _ : xs) = get1 xs
		skip1 (_ : xs) = get2 xs
	\end{verbatim}
What is the stream \texttt{xs :: Str Int} computed by the network ''Kahn'', i.e., what precise sequence of integer values does \texttt{xs} consist of?
Give the first 10 values of the stream and explain the generation principle.

\begin{figure*}[!t]
\vspace{-.5em}
	\centerline{\subfloat[Network ''Kahn'']{\includegraphics[width=.25\textwidth]{ws1516-1}}
		\hfil
		\subfloat[Refined Network ''Kahn'']{\includegraphics[width=.5\textwidth]{ws1516-2}}
	}
	\caption{Dataflow networks ''Kahn'' and ''Kahn*''}
	\label{img:fig1}
\end{figure*}


	\item Now consider the data flow network on the right of \autoref{img:fig1}, called "Kahn*" which is the same as ''Kahn'' but in which the node \texttt{kf} has been instantiated by the up-sampling node \texttt{merge} and \texttt{kg} has been implemented by two down-sampling nodes \texttt{when}.
	More precisely, we have
	\begin{verbatim}
	kf ys0 ys1 = merge cs0 ys0 ys1
	kg xs = (xs 'when' cs1, xs 'when' cs2)
	cs0 = ...
	cs1 = ...
	cs2 = ...
	\end{verbatim}
	with some Boolean clock streams \texttt{cs0,cs1,cs2 :: Str Bool} and the definition of \texttt{merge} and \texttt{when} from the lectures:
	\begin{verbatim}
	merge :: Str Bool -> Str a -> Str a -> Str a
	merge (True:cs) (x:xs) ys = x : (merge cs xs ys)
	merge (False:cs) xs (y:ys) = y : merge cs xs ys
	
	when :: Str a -> Str Bool -> Str a
	when (x:xs) (True:cs)  = x : (when xs cs)
	when (x:xs) (False:cs) = when xs cs
	\end{verbatim}
	Give a Haskell definition of the clock stream \texttt{cs0,cs1,cs2 :: Str Bool} such that the network "Kahn*" computes exactly the same stream \texttt{xs} as the network ''Kahn'' does with the nodes \texttt{kf} and \texttt{kg} from the previous part of this question.
\end{enumerate}
\item Aufgabe 3
\begin{enumerate}
	\item It generally depends on the evaluation strategy wether or not an expression $e$ reduces to a value, i.e., if there exists a sequence of reductions $e\twoheadrightarrow_R v$ such that $v\not\rightarrow_R$.
Such an expression $v$ is called a normal form of $e$ for the chosen evaluation strategy.\\[12pt]
Consider the expression $e_1=_{df}(EF)(EF)(\lambda x.x)$ and $e_2=_{df}(DF)(DF)(\lambda x.x)$ where
$$ D=_{df}\quad \lambda x.\lambda y.x(\lambda z.y y z)$$
$$E =_{df}\quad\lambda x.\lambda y.x(yy)$$
$$F=_{df}\quad\lambda h.\lambda x.x$$
Discuss the termination properties of the two expressions $e_1$ and $e_2$ under both the lazy and eager reduction strategies.
In other words, decide which of the two expressions, if any, reduces to a normal form under \textbf{lazy reduction} and which of the two expressions, if any, reduces to a normal form under \textbf{eager reduction}.

\textbf{Justify your answers by giving explicit reduction steps making clear the difference between the lazy and eager reduction strategies!}
	\item What is the fixed point combinator $Y$ fopr eager evaluation?
Explain its purpose and give an explicit coding of $Y$ as closed $\lambda$-expression.
\end{enumerate}
\end{enumerate}
\end{document}