← Back to Scala Course | Chapter 9: Functional Programming | Lesson 7 of 8

Function Composition क्या है

Function composition दो functions को इस तरह chain करता है कि एक का output दूसरे में जाए, जैसे एक assembly line। andThen और compose इन्हें किसी भी क्रम में जोड़ते हैं।

In this page:

  1. Function Composition
Syntax
scala
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

markup
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
}
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. #}
आम गलतियां
  1. andThen और compose को मिला देना, जबकि f andThen g पहले f चलाता है और f compose g पहले g चलाता है।
  2. ऐसे functions को compose करना जिनकी types मेल न खाएं, जैसे एक String result किसी Int function में जाना।
  3. यह भूल जाना कि result एक नया function है और इसे अब भी किसी argument के साथ call करना होगा।
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.