Programming in Scala”
fpiscompanion
fpiscompanion
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Chapter notes 18<br />
case class Moore[S, I, A](t: (S, I) => S, g: S => A)<br />
Together with an <strong>in</strong>itial state s of type S. Here:<br />
• S is the set of states.<br />
• I is the <strong>in</strong>put alphabet.<br />
• A is the output alphabet.<br />
• t is the transition function mapp<strong>in</strong>g the state and an <strong>in</strong>put value to the next state.<br />
• g is the output function mapp<strong>in</strong>g each state to the output alphabet.<br />
As with Mealy mach<strong>in</strong>es, we could model the transition function and the output function as a s<strong>in</strong>gle<br />
function:<br />
type Moore[S, I, A] = S => (I => S, A)<br />
S<strong>in</strong>ce both the transition function t and the output function g take a value of type S, we can take<br />
that value as a s<strong>in</strong>gle argument and from it determ<strong>in</strong>e the transition function of type I => S as well<br />
as the output value of type A at the same time.<br />
Mealy and Moore mach<strong>in</strong>es are related <strong>in</strong> a way that is <strong>in</strong>terest<strong>in</strong>g to explore.<br />
Lenses<br />
If we specialize Moore so that the <strong>in</strong>put and output types are the same, we get a pair of functions t:<br />
(S, A) => S and g: S => A. We can view these as (respectively) a “getter” and a “setter” of A values<br />
on the type S:<br />
get: S => A<br />
set: (S, A) => S<br />
Imag<strong>in</strong>e for example where S is Person and A is Name.<br />
type Name = Str<strong>in</strong>g<br />
case class Person(name: Name, age: Int)<br />
A function getName would have the type Person => Name, and setName would have the type<br />
(Person, Name) => Person. In the latter case, given a Person and a Name, we can set the name<br />
of the Person and get a new Person with the new name.<br />
The getter and setter together form what’s called a lens. A lens “focuses” on a part of a larger<br />
structure, and allows us to modify the value under focus. A simple model of lenses is: