[英]Scala Fold Function Mismatch type
I have a FoldSignal
case class as following. 我有一个如下的
FoldSignal
案例类。
/**
* Represents a signal that is manipulated to using the functional "fold" operation
* @param s Underlying signal
* @param start seed for the fold
* @param f fold function
*/
case class FoldSignal[T, U](s: Signal[T], start: U, f: (U, T) => U) extends Signal[U]
And I used it to create a function in Signal[T]: 我用它在Signal [T]中创建一个函数:
sealed trait Signal[T]{
...
/**
* Return a delta of signals in windows
*/
def delta(implicit ev: T =:= (_, DateTime) ): Signal[T] = {
def foldFun(queue: List[T], t: T) = {
println(queue(0))
queue(0)._1
}
FoldSignal(this, Nil, foldFun)
}
...
}
where Signal[T] is a sealed trait: 其中Signal [T]是密封特征:
/**
* Signal is a AST object represents a value that is continuously emitted. It does
* not specify anything about the source of the signal.
*/
sealed trait Signal[T] {...}
And it comes up an error: 它出现了一个错误:
Error:(71, 22) type mismatch;
found : scala.collection.immutable.Nil.type
required: T
FoldSignal(this, Nil, foldFun)
^
Could someone help me, please! 有人可以帮我吗! Thanks!
谢谢!
You've messed up types with your (_, DateTime)
- your foldFun
should return U
(see f: (U, T) => U
) which is List[T]
but you return U.head._1
which is Any
(as a result of resolving of your existential type _
) 您已经用
(_, DateTime)
弄乱了类型-您的foldFun
应该返回U
(请参阅f: (U, T) => U
),它是List[T]
但是您返回U.head._1
,它是Any
(由于解决了您的存在类型_
)
You see what you see because Scala can't infer a type (for Nil
) here (type inference doesn't see connection between f
and start
parameters), try: 您会看到您所看到的,因为Scala在这里无法推断类型(对于
Nil
)(类型推断看不到f
和start
参数之间的连接),请尝试:
FoldSignal(this, List.empty[T], foldFun)
Another approach is to to separate f
and start
into different parameter lists ( start
should be first - so T
is gonna be inferred first from it): 另一种方法是将
f
分开并start
进入不同的参数列表( start
应在第一位-因此首先要从中推断出T
):
def makeFoldSignal[T, U](s: Signal[T], f: (U, T) => U)(start: U)
May be related and explains about type inference a bit (in comparison with Haskell): 1 :: List[Nothing] in foldLeft 可能与类型推理有关(与Haskell比较) ,并作了一些解释 : 1 :: foldLeft中的List [Nothing]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.