gpt4 book ai didi

scala - 从函数参数推断类型参数

转载 作者:行者123 更新时间:2023-12-01 10:42:23 25 4
gpt4 key购买 nike

another stackoverflow question 的上下文中,我有这个片段:

def orderedGroupBy[T, P](seq: Traversable[T], f: T => P): Traversable[Tuple2[P, Traversable[T]]] = {
@tailrec
def accumulator(seq: Traversable[T], f: T => P, res: List[Tuple2[P, Traversable[T]]]): Traversable[Tuple2[P, Traversable[T]]] = seq.headOption match {
case None => res.reverse
case Some(h) => {
val key = f(h)
val subseq = seq.takeWhile(f(_) == key)
accumulator(seq.drop(subseq.size), f, (key -> subseq) :: res)
}
}
accumulator(seq, f, Nil)
}

我想像使用 .groupBy 一样使用它,例如:

orderedGroupBy(1 to 100, (_ / 10))

但是编译器报错说没有足够的类型信息

<console>:10: error: missing parameter type for expanded function ((x$1) => x$1.$div(10))
orderedGroupBy(1 to 100, (_ / 10))

执行此操作的惯用方法是什么?

最佳答案

您可以柯里化(Currying)参数,以便 T 仅从 seq: Traversable[T] 推断。

def orderedGroupBy[T, P](seq: Traversable[T])(f: T => P): Traversable[Tuple2[P, Traversable[T]]] = ???

scala> orderedGroupBy(1 to 100)(_ / 10)
res110: Traversable[(Int, Traversable[Int])] = List((0,Range(1, 2, 3, 4, 5, 6, 7, 8, 9)), (1,Range(10, 11, 12, 13, 14, 15, 16, 17, 18, 19)), (2,Range(20, 21, 22, 23, 24, 25, 26, 27, 28, 29)), (3,Range(30, 31, 32, 33, 34, 35, 36, 37, 38, 39)), (4,Range(40, 41, 42, 43, 44, 45, 46, 47, 48, 49)), (5,Range(50, 51, 52, 53, 54, 55, 56, 57, 58, 59)), (6,Range(60, 61, 62, 63, 64, 65, 66, 67, 68, 69)), (7,Range(70, 71, 72, 73, 74, 75, 76, 77, 78, 79)), (8,Range(80, 81, 82, 83, 84, 85, 86, 87, 88, 89)), (9,Range(90, 91, 92, 93, 94, 95, 96, 97, 98, 99)), (10,Range(100)))

关于scala - 从函数参数推断类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29267354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com