Higher-Order Functions क्या हैं
एक higher-order function या तो किसी दूसरे function को input के रूप में लेता है या एक वापस देता है, जैसे कोई coach जो चलाने के लिए एक play देता है। यह आपको actions को साधारण values की तरह treat करने देता है।
In this page:
Syntax
def function_name(f: InputType => OutputType, value: InputType): OutputType = f(value)
def returns_function(): InputType => OutputType = (x: InputType) => expression
Higher-Order Functions
एक higher-order function या तो किसी दूसरे function को parameter के रूप में लेता है, एक function return करता है, या दोनों -- Scala में functions first-class values हैं, जिन्हें किसी भी दूसरी value की तरह store और pass किया जा सकता है।
यह Scala की functional programming style की नींव है, जो आपको सिर्फ data नहीं बल्कि behavior को भी parameterize करने देती है। map और filter जैसे कई standard collection methods higher-order functions हैं।
Note:
function type
Int => Int एक ऐसे function को describe करता है जो एक Int लेता है और एक Int return करता है, जिसे parameter type के रूप में उपयोग किया जा सकता है।उदाहरण: Higher-Order Functions
object Main extends App {
def applyTwice(f: Int => Int, x: Int): Int = {
f(f(x))
}
def addOne(n: Int): Int = n + 1
println(applyTwice(addOne, 5))
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- method खुद की जगह method का result पास करना, जैसे
applyTwice(addOne(1), 5), जबकि एक function की उम्मीद की जाती है। - type गलत करना, जैसे
f: Int => Intजबकि एक ऐसा function पास करना जो दो arguments लेता है। - function parameter के return type को भूल जाना, जिससे higher-order function पढ़ना मुश्किल हो जाता है।
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: