[英]Scala: Why is there a type mismatch in this function?
我有這個 function,其目標是在學生列表中找到一個具有所需數量的學生。
type Number = Int
type Name = String
type Student = (Number, Name)
type Students = List[Student]
def searchStudentFold(t: Students, n: Number) : Option[Student] = {
(t foldRight None) ( (x, t) => if(x._1 == n) Some(x) else t)
}
但是,當我嘗試返回 Some(x) 時,由於類型不匹配,這不起作用。 它說所需的類型是None.type
並且找到了Some[(Number, Name)]
。 但我想返回的正是Some[(Number, Name)]
。
這是編譯錯誤消息:
type mismatch;
found : Some[Ficha5.Class.Student]
(which expands to) Some[(Int, String)]
required: None.type
(t foldRight None) ( (x, t) => if(x._1 == n) Some(x) else t)
您需要提供 output 類型,因為 fold 不是逆變的,不允許將 None 向上轉換為 Option。
請注意folfLeft
在遍歷集合時在內存方面更好。 foldRight
在列表中以“錯誤的方式”出現。 此外,您可以通過簡單的find
來完成您正在做的事情
type Number = Int
type Name = String
type Student = (Number, Name)
type Students = List[Student]
def searchStudentFoldRight(t: Students, n: Number): Option[Student] = {
t.foldRight[Option[Student]](None)((x, t) => if (x._1 == n) Some(x) else t)
}
def searchStudentFoldLeft(t: Students, n: Number): Option[Student] = {
// Alternative way to upcast None, same result
t.foldLeft(None:Option[Student])((t, x) => if (x._1 == n) Some(x) else t)
}
def searchStudentFind(t: Students, n: Number): Option[Student] =
t.find(_._1 == n)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.