Skip to content

Commit

Permalink
A strawman for aggregate literals
Browse files Browse the repository at this point in the history
A test case that shows that we can have an "inline type class" that allows
to use a typeclass-based scheme for sequence literals where instances can
be created with macros.
  • Loading branch information
odersky committed Nov 20, 2024
1 parent 58f88a6 commit 3fb949c
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
6 changes: 6 additions & 0 deletions tests/pos/seqlits.check
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
last was evaluated
last was evaluated
Seq List(1, 2, 3, 4)
Vector Vector(1, 2, 3, 4)
last was evaluated
Task with elems List(1, 2, 3, 4)
41 changes: 41 additions & 0 deletions tests/pos/seqlits.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import reflect.ClassTag

/** Some delayed computation like a Mill Task */
case class Task[T](body: () => T)

object SeqLits:

/** A typeclass to map sequence literals with `T` elements
* to some collection type `C`.
*/
trait FromArray[T, +C]:
inline def fromArray(inline xs: IArray[T]): C

/** An emulation of a sequence literal like [1, 2, 3]. Since we don't have that
* syntax yet, we express it here as `seqLit(1, 2, 3)`.
*/
inline def seqLit[T: ClassTag, C](inline xs: T*)(using inline f: FromArray[T, C]): C =
f.fromArray(IArray(xs*))

/** Straightfoward mapping to Seq */
given [T] => FromArray[T, Seq[T]]:
inline def fromArray(inline xs: IArray[T]) = Seq(xs*)

/** A more specific mapping to Vector */
given [T] => FromArray[T, Vector[T]]:
inline def fromArray(inline xs: IArray[T]) = Vector(xs*)

/** A delaying mapping to Task */
given [T] => FromArray[T, Task[Seq[T]]]:
inline def fromArray(inline xs: IArray[T]) = Task(() => Seq(xs*))

def last: Int = { println("last was evaluated"); 4 }

val s: Seq[Int] = seqLit(1, 2, 3, last)
val v: Vector[Int] = seqLit(1, 2, 3, last)
val t: Task[Seq[Int]] = seqLit(1, 2, 3, last)

@main def Test =
println(s"Seq $s")
println(s"Vector $v")
println(s"${t.getClass.getSimpleName} with elems ${t.body()}")

0 comments on commit 3fb949c

Please sign in to comment.