根據實現,您需要傳遞函數A => F[Boolean]
,如F: Applicative
。 filterM
越過列表,爲謂詞傳遞的過濾元素(返回F[true]
),並最終將此List
轉換爲F
。
了一下簡單的例子:
List(1, 2, 3).filterM[Option](_.some.map(_ % 2 == 0)) // Some(List(2))
注意,這給你自由的額外程度,不能只考慮true
或false
,但也None
。您可以嘗試讓不同的應用程序掌握這個概念。
在您輸入的示例中,List
也是Applicative。這樣,發生了什麼(因爲它是遞歸的,更容易從走到底):
1)當你在列表的末尾 - 你只是得到一個空列表
2)你有一個清單3 :: Nil
。將謂詞應用到3
會給你List(true, false)
。所以,你正在採取整個List(3)
和尾部List()
。
3)接下來是2
。 2 -> true :: false
它映射到head
:: head :: tail
這就是List(2) :: List(2, 3)
。追加到你以前的東西,你會得到List(List(2, 3), List(2), List(3), List())
4)現在是最後一步,你會得到一個。與true
的列表中的每個列表相同,您可以將1
添加到false
的其餘列表中。
List(List(1, 2, 3), List(1, 2), List(1, 3), List(1), List(2, 3), List(2), List(3), List())
我加了一些記錄,弄清楚發生了什麼:
current list: List(1, 2, 3)
current list: List(2, 3)
current list: List(3)
current list: List()
filtered value: List(List())
taking head and tail : List(3)
taking tail: List()
filtered value: List(List(3), List())
taking head and tail : List(2, 3)
taking head and tail : List(2)
taking tail: List(3)
taking tail: List()
filtered value: List(List(2, 3), List(2), List(3), List())
taking head and tail : List(1, 2, 3)
taking head and tail : List(1, 2)
taking head and tail : List(1, 3)
taking head and tail : List(1)
taking tail: List(2, 3)
taking tail: List(2)
taking tail: List(3)
taking tail: List()
List(List(1, 2, 3), List(1, 2), List(1, 3), List(1), List(2, 3), List(2), List(3), List())