Created
November 24, 2011 19:23
-
-
Save zah/1392058 to your computer and use it in GitHub Desktop.
The case for Option[T]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Option[T] and safe navigation: | |
| # Some languages have a specialized syntax for what is usually called "safe navigation" | |
| foo?.bar[10]?.baz | |
| # Option[T] could be implemented as a proxy type that rewrites any operation on it | |
| # as a operation applied to the stored value (if there is any) | |
| # The original example then becomes: | |
| Option(foo).bar[10].baz # returns Option[type(baz)] | |
| # Another point to note: proxy types used in this fashion are pretty much equivalent to Haskell's monads | |
| # Option[T] and the HLO: | |
| # One can write a rule similar to this: | |
| template { if(x): body } (x: Option[T]) = | |
| if(x.hasValue): | |
| var x = x.value | |
| block: body | |
| # Thus achieving both achiving both convenient syntax and perfect generated code | |
| # Other similar clever tricks are possible with "symbol attached user properties" to implement the type state logic | |
| # And finally, Option[T] is a meta-type (type describing additional properties of another type) | |
| # using meta types is good because they encode the intention of the library writter and allow | |
| # algorithms similar to the above to be executed over the program as a whole. |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For completeness, here is the other approach of optimizing Option[T] using "attached symbol properties" (cookies):
The if statement involving Option[T] is transformed to:
then the proxy macro code in Option[T] detects the ProvenToHaveValue "cookie" and generates code without checks