← Back to Scala Course | Chapter 5: Functions | Lesson 7 of 7

रिकर्सिव Functions

एक recursive function किसी problem को खुद को उसके छोटे version पर call करके हल करता है, जैसे सबसे छोटी तक Russian dolls खोलना। इसे एक रुकने की जगह चाहिए नहीं तो यह हमेशा चलता रहेगा।

In this page:

  1. Recursive Functions
Syntax
scala
def function_name(n: Int): Int = {
  if (n <= 1) base_value    // base case
  else n * function_name(n - 1)    // recursive step
}

Recursive Functions

एक Scala function खुद को call कर सकता है, जिससे recursion बनता है, जब तक इसे रोकने वाला एक base case हो। Recursive functions को explicit return type annotation चाहिए (सरल functions के विपरीत जहां यह अक्सर infer हो सकता है), क्योंकि compiler किसी recursive function के return type को उसके अपने body से infer नहीं कर सकता।

@tailrec annotation को compile time पर यह verify करने के लिए जोड़ा जा सकता है कि कोई recursive call tail position में है और call stack बढ़ाने के बजाय एक loop में optimize हो जाएगी।

Warning: किसी recursive function का return type explicitly declare होना चाहिए -- Scala इसे ऐसे body से infer नहीं कर सकता जो खुद को call करता है।

उदाहरण: Recursive Functions

markup
object Main extends App {
  def factorial(n: Int): Int = {
    if (n <= 1) 1
    else n * factorial(n - 1)
  }

  println(factorial(5))
}
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. base case छोड़ देना, जिससे factorial हमेशा खुद को call करता रहता है और StackOverflowError में खत्म होता है।
  2. factorial(20) के लिए Int का उपयोग करना, जो चुपचाप overflow हो जाता है और गलत number देता है; Long या BigInt का उपयोग करें।
  3. यह भूल जाना कि recursion को declared return type चाहिए, जिससे def factorial(n: Int) = ... error देता है।
चैप्टर सारांश
  • Functions के parameters और return types होते हैं, और default parameters, named arguments, और varargs का उपयोग कर सकते हैं।
  • Nested functions helpers को local रखते हैं।
  • Recursive functions समस्याओं को हल करने के लिए खुद को call करते हैं।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 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.