Skip to content

Instantly share code, notes, and snippets.

@zah
Created November 24, 2011 19:23
Show Gist options
  • Select an option

  • Save zah/1392058 to your computer and use it in GitHub Desktop.

Select an option

Save zah/1392058 to your computer and use it in GitHub Desktop.
The case for Option[T]
# 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.
@Araq
Copy link

Araq commented Nov 27, 2011

Ok, fair enough. ;-)

However, the HLO can also easily deal with

if exists(key):
  var value = get(key)

@zah
Copy link
Author

zah commented Nov 28, 2011

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:

if x.hasValue:
   addScopedSymProp(x, "ProvenToHaveValue", true)
   body

then the proxy macro code in Option[T] detects the ProvenToHaveValue "cookie" and generates code without checks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment