Scala 中布尔值的元组和谓词元组

A tuple and a tuple of predicates to boolean in Scala

提问人:Koosha 提问时间:10/21/2023 更新时间:10/21/2023 访问量:73

问:

关于如何在 Scala 3 中实现以下函数的任何想法?

我可以接受或不接受,一般来说,轻微的语法更改是可以的(即使是宏也可以)。 但是我不知道该怎么做没有.inlineasInstanceOf

type Pred[A] = A => Boolean

/** Computes values of predicates and combines them with `&&`.
  * 
  * The implementation does not use `asInstanceOf` or `isInstanceOf` */
inline def tupled[Args <: Tuple](inline preds: Tuple.Map[Args,Pred], inline args: Args): Boolean

例:

val pred: (Int => Boolean, Int => Boolean) = (_ < 0, _ > 0)

println(tupled[(Int, Int)](pred)( 1, 2)) // should print false
println(tupled[(Int, Int)](pred)(-1, 2)) // should print true
scala 元组 scala-3

评论

0赞 Gaël J 10/21/2023
到目前为止,你尝试了什么?你为什么需要?你真的需要使用元组还是可以?asInstanceOfList
0赞 Mateusz Kubuszok 10/21/2023
@GaëlJ List 将要求所有谓词都在同一@Koosha上工作,我想需要类似的东西。Atupled((_.nonEmpty, _ > 0), ("string", 10))

答:

6赞 Eastsun 10/21/2023 #1

这个怎么样:

trait Reducer[Args <: Tuple, Preds <: Tuple]:
    def reduce(args: Args, preds: Preds): Boolean

object Reducer:
    given Reducer[EmptyTuple, EmptyTuple] = (args, preds) => true

    given [H, Args <: Tuple, Preds <: Tuple](using r: Reducer[Args, Preds]): Reducer[H *: Args, (H => Boolean) *: Preds] with
        def reduce(args: H *: Args, preds: (H => Boolean) *: Preds): Boolean = (args, preds) match
            case (ha *: ta, hp *: tp) => hp(ha) && r.reduce(ta, tp)

type Pred[A] = A => Boolean

/** Computes values of predicates and combines them with `&&`.
 *
 * The implementation does not use `asInstanceOf` or `isInstanceOf` */
def tupled[Args <: Tuple](preds: Tuple.Map[Args, Pred], args: Args)
                         (using r: Reducer[Args, Tuple.Map[Args, Pred]]): Boolean =
    r.reduce(args, preds)


scala> val pred: (Int => Boolean, Int => Boolean) = (_ < 0, _ > 0)
     |
     | println(tupled[(Int, Int)](pred, ( 1, 2))) // should print false
     | println(tupled[(Int, Int)](pred, (-1, 2)))
false
true

如果交换参数,我们可以忽略类型参数:

scala> def tupled2[Args <: Tuple](args: Args, preds: Tuple.Map[Args, Pred])
     |                          (using r: Reducer[Args, Tuple.Map[Args, Pred]]): Boolean =
     |     r.reduce(args, preds)
     |
def tupled2[Args <: Tuple](args: Args, preds: Tuple.Map[Args, Pred])(using r: Reducer[Args, Tuple.Map[Args, Pred]]): Boolean

scala> val pred: (Int => Boolean, Int => Boolean) = (_ < 0, _ > 0)
     |
     | println(tupled2(( 1, 2), pred)) // should print false
     | println(tupled2((-1, 2), pred))

评论

0赞 stefanobaghino 10/23/2023
好东西!:)这个周末我快速浏览了一下这个问题,但我错过了“减少”部分,并决定不继续前进。我认为值得与 Scala 团队联系,看看他们是否会考虑将其包含在标准库中。