[英]What parameters do I pass to 'filter' function in Scala
我無法理解這個涉及 lambda 表達式的 Scala 代碼:
object ScalaList {
case class Student(rollNo : Int, name : String, marks : Int)
val students= List(Student(1,"A",10),Student(2,"B",14))
var toppers = students.filter(s=>s.marks>10) //> toppers : List[ScalaList.Student] = List(Student(2,B,14))
}
它有效,但過濾器 function 采用我沒有定義的參數“s”。 什么是's'。 另外,如果這是 pandas,我想我需要提供一個 axis=1 參數。 為什么我在 Scala 中不需要它
也許比較 Python 實現會有所幫助
>>> from pydantic import BaseModel
>>>
>>> class Student(BaseModel):
... rollNo: int
... name: str
... marks: int
...
>>> students = [
... Student(rollNo=1, name="A", marks=10),
... Student(rollNo=2, name="B", marks=14)
... ]
>>>
>>> list(filter(lambda s: s.marks > 10, students))
[Student(rollNo=2, name='B', marks=14)]
具有類似的 Scala 實現
scala> case class Student(
| rollNo: Int,
| name: String,
| marks: Int
| )
| val students = List(
| Student(1, "A", 10),
| Student(2, "B", 14)
| )
| students.filter(s => s.marks > 10)
class Student
val students: List[Student] = List(Student(1,A,10), Student(2,B,14))
val res0: List[Student] = List(Student(2,B,14))
我們在哪里看到 Scala lambda
s => s.marks > 10
類似於 Python lambda
lambda s: s.marks > 10
這應該清楚地表明,聲明的 lambda 參數s
成為 lambda 主體內的局部變量。
Consider Scala API documentation for List#filter as well as Scala for Python Developers section of Scala 3 Book.
請注意, filter
方法的參數不是s
,而是整個s => s.marks > 10
:這是定義匿名function 的語法,它接受一些s
並返回其marks
字段的比較結果與文字10
。 在這種情況下, s
只是 function 的參數的組成名稱,就像它被定義為以下示例中的方法一樣:
def marksGreaterThan10(s: Student): Boolean = s.marks > 10
可能會讓一些人對語法感到困惑的一件事是編譯器本身能夠根據您的輸入推斷類型,使其非常緊湊和可讀,但對於新手來說可能有點不透明。 請注意,如果沒有適當的上下文(即正在過濾Student
的列表,因此 function 的輸入類型必須是Student
),編譯器會抱怨missing parameter type
,您需要提供一個,如以下示例(我將匿名 function分配給變量,以便我可以在程序的其他部分使用它):
val marksGreaterThan10 = (s: Student) => s.marks > 10
Note that both a method and a function can be passed to a higher-order function (a function that can take a function as a parameter or return one as an output) like filter
.
final case class Student(marks: Int)
val marksGreaterThan10Function = (s: Student) => s.marks > 10
def marksGreaterThan10Method(s: Student): Boolean = s.marks > 10
val students = Seq(Student(1), Student(11))
// Both of these returns `Seq(Student(11))`
students.filter(marksGreaterThan10Function)
students.filter(marksGreaterThan10Method)
您可以在 Scastie 上使用上面的代碼。
如果您熟悉 Java lambda 表達式語法, ->
或多或少等同於=>
並且您會編寫如下內容:
students.stream().filter(s -> s.marks > 10)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.