typelevel / simulacrum

First class syntax support for type classes in Scala
BSD 3-Clause "New" or "Revised" License
937 stars 61 forks source link

Quickstart documentation for simulacrum (and its annotations) #28

Open pjan opened 9 years ago

pjan commented 9 years ago

cfr: https://github.com/non/algebra/pull/54

It would probably be good to have a quickstart documentation on top of the Readme, documenting all the annotations, for easier adoption.

mpilquist commented 9 years ago

:+1:

Any preference for quickstart vs adding docs on @noop directly to the README?

pjan commented 9 years ago

I believe the project would benefit from something in the style of

@typeclass trait Monoid[A] {
  def empty: A
  @op("|+|") def combine(x: A, y: A): A
  def append(x: A, y: A): A = combine(x, y)
  @noop def combineN(a: A, n: Int): A =
    if (n < 0) throw new IllegalArgumentException("Repeated combining for monoids must have n >= 0")
    else if (n == 0) empty
    else append(a, combineN(a, n-1))
}

creates a Monoid typeclass for which you can use it's methods as follows:

// Creating a Monoid instance:
implicit val intSumMonoid =
  new Monoid[Int] {
    val empty: 0
    def combine(x: Int, y: Int) = x + y
  }

// Importing the implicit Monoid operations
import Monoid.ops._

// invoking each of the Monoid operations
val intEmpty = Monoid[Int].empty

val sum1 = Monoid[Int].combine(1, 2)
val sum2 = 1 |+| 2 // the @op("|+|") annotation generates the |+| infix operator

val sum3 = Monoid[Int].append(1, 2)
val sum4 = 1 append 2 // without annotation, you get an infix operator with the method name

val multi = Monoid[Int].combineN(2, 4) // the @noop annotation prevents the creation of an infix operator

I might be biased as I'm familiar with the library. Maybe @non or @johnynek could chime in as well?

johnynek commented 9 years ago

This looks good. I'd also like a full list of all the annotations and what things expand to. For instance, I didn't see a doc on noop and had to look that up. Not sure if there are others I don't know about. I'm not 100% clear on what I can add to the companion object without causing problems for the macro.

guizmaii commented 7 years ago

Agree with @pjan. I have just understood some subtleties thanks to this issue :)