05.03.2016 Views

Programming in Scala”

fpiscompanion

fpiscompanion

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter notes 44<br />

trait Translate[F[_],G[_]] {<br />

}<br />

def apply[A](f: F[A]): G[A]<br />

Although values must be monomorphic, methods <strong>in</strong> Scala can of course be polymorphic, so we<br />

simply <strong>in</strong>troduce a new first-class type conta<strong>in</strong><strong>in</strong>g a polymorphic method. Unfortunately, this means<br />

that various polymorphic methods we might have ly<strong>in</strong>g around must be explicitly wrapped <strong>in</strong><br />

Translate:<br />

def headOption[A](a: List[A]): Option[A]<br />

Even though headOption is polymorphic, we would need to explicitly wrap it <strong>in</strong> a Translate[List,Option]<br />

if we ever needed to use it polymorphically <strong>in</strong> a first-class way. Another drawback of this approach<br />

is that we require separate versions of Translate for different “shapes” of the <strong>in</strong>put and output type<br />

constructors–for <strong>in</strong>stance, <strong>in</strong> chapter 14, we def<strong>in</strong>e a type RunnableST, which would typically just<br />

be represented us<strong>in</strong>g a universally quantified ord<strong>in</strong>ary value, without need<strong>in</strong>g wrapp<strong>in</strong>g <strong>in</strong> a new<br />

type.<br />

L<strong>in</strong>ks<br />

See Free Monads and Free Monoids¹⁸⁰ for more <strong>in</strong>formation about what “free” means.<br />

Notes on chapter 14: Local effects and mutable state<br />

The ST data type covered <strong>in</strong> this chapter was first <strong>in</strong>troduced <strong>in</strong> Lazy Functional State Threads¹⁸¹.<br />

The general idea, of us<strong>in</strong>g universal quantification to uniquely tag variables and enforce scop<strong>in</strong>g,<br />

is also useful <strong>in</strong> other situations. For <strong>in</strong>stance, we can use the same idea to enforce a ‘safe’ API for<br />

access<strong>in</strong>g file handles, prevent<strong>in</strong>g a file handle from be<strong>in</strong>g referenced after it passes out of scope.<br />

Here is a sketch of an API:<br />

¹⁸⁰http://blog.higher-order.com/blog/2013/08/20/free-monads-and-free-monoids/<br />

¹⁸¹http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.50.3299

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!