Introduction
Uniqueness typing is best explained using an example. Consider a function readLine
that reads the next line of text from a given file:
Now doImperativeReadLineSystemCall
reads the next line from the file using an OS-level system call which has the side effect of changing the current position in the file. But this violates referential transparency because calling it multiple times with the same argument will return different results each time as the current position in the file gets moved. This in turn makes readLine
violate referential transparency because it calls doImperativeReadLineSystemCall
.
However, using uniqueness typing, we can construct a new version of readLine
that is referentially transparent even though it's built on top of a function that's not referentially transparent:
The unique
declaration specifies that the type of f
is unique; that is to say that f
may never be referred to again by the caller of readLine2
after readLine2
returns, and this restriction is enforced by the type system. And since readLine2
does not return f
itself but rather a new, different file object differentF
, this means that it's impossible for readLine2
to be called with f
as an argument ever again, thus preserving referential transparency while allowing for side effects to occur.
Read more about this topic: Uniqueness Type
Famous quotes containing the word introduction:
“The role of the stepmother is the most difficult of all, because you cant ever just be. Youre constantly being testedby the children, the neighbors, your husband, the relatives, old friends who knew the childrens parents in their first marriage, and by yourself.”
—Anonymous Stepparent. Making It as a Stepparent, by Claire Berman, introduction (1980, repr. 1986)
“My objection to Liberalism is thisthat it is the introduction into the practical business of life of the highest kindnamely, politicsof philosophical ideas instead of political principles.”
—Benjamin Disraeli (18041881)
“For the introduction of a new kind of music must be shunned as imperiling the whole state; since styles of music are never disturbed without affecting the most important political institutions.”
—Plato (c. 427347 B.C.)