Scala 3中的fusemap宏

发布于 2025-02-06 07:41:17 字数 1209 浏览 3 评论 0原文

遵循元编程教程在这里fusemap示例可以使用。我拥有的宏是(在宏中对象)

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

,并像我期望看到在Compile上打印出的简化代码一样在单独的文件中调用


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无需任何事情”。

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".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傻比既视感 2025-02-13 07:41:18

我能够通过将论点提交简化内联来获得这项工作

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

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) }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文