【问题标题】:fuseMap macro in scala 3scala 3中的fuseMap宏
【发布时间】:2022-08-04 00:54:27
【问题描述】:

遵循元编程教程here,我无法让 fuseMap 示例工作。我拥有的宏是(在macros 对象中)

  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) }

并在单独的文件中调用它


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\")

}

我希望看到在编译时打印出简化的代码,但我看到的是“fuseMap 没有做任何事情”。

    标签: scala macros scala-3


    【解决方案1】:

    我能够通过将参数设置为simplify inline 来完成这项工作

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 2022-09-30
      • 2022-09-30
      • 2021-04-10
      • 1970-01-01
      相关资源
      最近更新 更多