Skip to content

Instantly share code, notes, and snippets.

@nicolasstucki
Last active July 14, 2016 12:35
Show Gist options
  • Save nicolasstucki/5beb73edc9f54effb7d8d2fe1f9c1914 to your computer and use it in GitHub Desktop.
Save nicolasstucki/5beb73edc9f54effb7d8d2fe1f9c1914 to your computer and use it in GitHub Desktop.

Stoic functions implementation

Support for stoic functions

@stoic and Stoical
trait Stoical
class stoic extends scala.annotation.StaticAnnotation

@stioc will go exclusively on of method definitions and will ensure that Stoical objects are captured by the function excepting through the parameters.

Stoic rules
  1. Can not capture values of type Stoical.
  2. Can not calling a method that returns a Stoical.
  3. Same rules apply for implicits.
Usage

The following code shows some simple examples.

class Foo
class Bar extends Stoical

val foo1   = new Foo
def foo2() = new Foo
val bar1   = new Bar
def bar2() = new Bar
def bar3(b: Bar) = ()

@stoic def baz() = {
  foo1          // OK 
  foo2()        // OK 
  bar1          // Disallow
  bar2()        // Disallow
  bar3(new Bar) // OK
}

@stoic def qux(bar1: Bar, bar2: () => Bar, bar3: Bar => ()) = {
  foo1          // OK
  foo2()        // OK
  bar1          // OK
  bar2()        // OK
  bar3(new Bar) // OK
}

Stoic function trait and lambda

Stoic functions should have trait just like functions:

trait StoicFunction1[-T, +R] extends Function[T, R] {
  @stoic def apply(e: T): R = ???
}

This will allow us to refer to a function that is stoical and to desugar lambdas into anonymous stoic functions.

val f: Int -> Unit = (e: Int) -> println(e)

// would be desugared into

val f: StoicFunction1[Int, Unit] = StoicFunction1[Int, Unit] {
  @stoic def apply(e: Int): Unit = println(e)
}

For capabilities

We would start by defining capabilities as being stoical.

trait Capability extends Stoical

We will also need additional constraints such as a pure function can not call a non pure one (unless the bottom capability is available). This is not the focus of this proposal and therfore will not go into details.

@nicolasstucki
Copy link
Author

After a discussion with Martin the following change in definition fas made:

  • remove trait Stoical and make a synthetic type in the compiler that is outside of the Any/Nothing lattice.

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