flatMap और for-comprehensions
In this page:
val result = collection.flatMap(x => other_collection(x))
val same = for {
x <- collection
y <- other_collection(x)
} yield y
flatMap and for-comprehensions
flatMap(f) हर element को एक नई collection (या Option) में map करता है और फिर उन सभी results को एक single collection में flatten कर देता है, जिससे वह nested collections बचती हैं जो सिर्फ map छोड़ देता। यह तब ज़रूरी है जब कोई transformation खुद हर input element के लिए शून्य, एक, या कई results produce करता हो।
yield वाला एक for comprehension एक syntactic sugar है जिसे compiler map/flatMap/filter calls की एक chain में translate करता है, यही वजह है कि दोनों approaches समस्याओं की एक ही class को हल करते हैं।
<- generators वाला एक for comprehension बिल्कुल nested flatMap/map calls के बराबर है -- compiler इसे इसी तरह desugar करता है।उदाहरण: flatMap and for-comprehensions
object Main extends App {
val words = List("hello", "world")
val letters = words.flatMap(w => w.toList)
println(letters)
val pairs = for {
x <- List(1, 2)
y <- List("a", "b")
} yield (x, y)
println(pairs)
}
Login to try C/C++/Java/PHP code in the editor
mapका उपयोग करना जब function एक collection return करता है, जिससेflatMapके flat result के बजाय एक nestedList[List[Char]]बन जाता है।flatMapको ऐसा function पास करना जो collection याOptionके बजाय एक single value return करे, जो एक type error देता है।- किसी
forcomprehension में collection types मिलाना, जैसे एकListऔर एकOption, जिससे एक confusing type error आता है।
- Higher-order functions,
map,filter, औरreduceसहित, functions लेते या return करते हैं। - Anonymous functions, closures, currying, और partial application लचीले functions बनाते हैं।
- Function composition और for-comprehensions के साथ
flatMapoperations को combine करते हैं।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: