Function Composition क्या है
Function composition दो functions को इस तरह chain करता है कि एक का output दूसरे में जाए, जैसे एक assembly line। andThen और compose इन्हें किसी भी क्रम में जोड़ते हैं।
In this page:
Syntax
val combined1 = f andThen g // g(f(x))
val combined2 = f compose g // f(g(x))
Function Composition
andThen और compose दो functions को एक नए में combine करते हैं: f andThen g पहले f चलाता है फिर उसका result g में डालता है, जबकि f compose g पहले g चलाता है फिर उसका result f में डालता है -- विपरीत order।
यह आपको छोटे, reusable, single-purpose functions से complex transformations बनाने देता है। Composition functional programming style का एक मुख्य गुण है, जो एक बड़े function की तुलना में छोटे टुकड़ों को जोड़ने को प्राथमिकता देता है।
Note:
f andThen gपहले f फिर g apply करता है (बाएं से दाएं)।f compose gपहले g फिर f apply करता है (दाएं से बाएं) -- इसे मिला देना आसान है।
उदाहरण: Function Composition
object Main extends App {
val addOne: Int => Int = _ + 1
val double: Int => Int = _ * 2
val addThenDouble = addOne andThen double
val doubleThenAdd = addOne compose double
println(addThenDouble(3)) // (3+1)*2 = 8
println(doubleThenAdd(3)) // (3*2)+1 = 7
}
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. #}
आम गलतियां
andThenऔरcomposeको मिला देना, जबकिf andThen gपहलेfचलाता है औरf compose gपहलेgचलाता है।- ऐसे functions को compose करना जिनकी types मेल न खाएं, जैसे एक
Stringresult किसीIntfunction में जाना। - यह भूल जाना कि result एक नया function है और इसे अब भी किसी argument के साथ call करना होगा।
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: