fuseMap macro in scala 3
Asked Answered
P

1

0

Following the metaprogramming tutorial here, I am unable to get the fuseMap example to work. The macro I have is (in macros object)

  def fuseMap[T: Type](x: Expr[List[T]])(using Quotes): Expr[List[T]] =
    println("Initial passed in x: " + x.show)
    x match {
      case '{
            type u
            type v
            ($ls: List[`u`])
              .map($f: `u` => `v`)
              .map($g: `v` => T)
          } =>
        '{ $ls.map(y => $g($f(y))) }
        val result = '{ $ls.map(y => $g($f(y))) }

        println(result.show)
        result
      case _ =>
        println("fuseMap didn't do anything")
        x
    }

  inline def simplify[T](x: List[T]): List[T] = ${ fuseMap('x) }

And calling it in seperate file like


object macrofun extends App {

  val l = List(1, 2, 3)
  val f = (x: Int) => x + 1
  val g = (y: Int) => y * 2

  val r = simplify {
    List(1, 2, 3)
      .map(f)
      .map(g)
  }

  println(s"Result of l is $r")

}

I would expect to see the simplified code printed out on compile but instead I see "fuseMap didn't do anything".

Pic answered 8/6, 2022 at 18:29 Comment(0)
P
3

I was able to get this work by making the argument to simplify inline like

inline def simplify[T](inline x: List[T]): List[T] = ${ fuseMap('x) }
Pic answered 9/6, 2022 at 0:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.