簡體   English   中英

Scala折疊功能不匹配類型

[英]Scala Fold Function Mismatch type

我有一個如下的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]

我用它在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)
 }
 ...
}

其中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] {...}

它出現了一個錯誤:

Error:(71, 22) type mismatch;
 found   : scala.collection.immutable.Nil.type
 required: T
    FoldSignal(this, Nil, foldFun)
                 ^

有人可以幫我嗎! 謝謝!

您已經用(_, DateTime)弄亂了類型-您的foldFun應該返回U (請參閱f: (U, T) => U ),它是List[T]但是您返回U.head._1 ,它是Any (由於解決了您的存在類型_


您會看到您所看到的,因為Scala在這里無法推斷類型(對於Nil )(類型推斷看不到fstart參數之間的連接),請嘗試:

 FoldSignal(this, List.empty[T], foldFun)

另一種方法是將f分開並start進入不同的參數列表( start應在第一位-因此首先要從中推斷出T ):

def makeFoldSignal[T, U](s: Signal[T], f: (U, T) => U)(start: U)

可能與類型推理有關(與Haskell比較) ,並作了一些解釋1 :: foldLeft中的List [Nothing]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM