Coding
AI Prompt for Recursive Functions
Write correct recursive functions with this AI prompt: base cases, step-by-step traces, stack-depth analysis, and an iterative fallback included.
The prompt
Role: You are a computer science instructor who writes elegant, correct recursive functions and explains them beautifully. Context: Language: [LANGUAGE]. Problem: [PROBLEM_DESCRIPTION]. Base case: [BASE_CASE]. Recursive insight: [RECURSIVE_INSIGHT, e.g. fib(n) = fib(n-1) + fib(n-2), or 'unknown — help me find it']. Task: 1) If the recursive insight is unclear, derive it first in plain English. 2) Write the recursive function with a clear base case and recursive step. 3) Trace it on a small input ([SMALL_INPUT]) showing each call and return. 4) Analyze the maximum recursion depth and time complexity. 5) Provide an iterative version as well, and say when to prefer each. Format: Insight first, then the recursive code, then the trace, then complexity analysis, then the iterative alternative with the when-to-use guidance. Ask for a recursion-depth budget: the maximum input size before the call stack overflows in your language, and the exact point where you must switch to the iterative version. This turns a theoretical warning into a concrete limit. Constraints: The base case must be explicit and obviously terminating. Warn if the recursion depth could exceed [LANGUAGE]'s limits for realistic inputs.
Variables to fill in
Replace each [variable] in the prompt with your own details:
[LANGUAGE] [PROBLEM_DESCRIPTION] [BASE_CASE] [RECURSIVE_INSIGHT] [SMALL_INPUT]
Example input
LANGUAGE=Python, PROBLEM=compute factorial of n, BASE_CASE=n=0 returns 1, LIMIT=handle n up to 1000 without hitting recursion limits
How to use this prompt
Always define the base case explicitly — it is the #1 source of recursion bugs. Ask for the trace on a small input to verify the logic before using it.
Tips for the best results
- Study the trace on paper once — recursion clicks when you see the call stack unwind.
- Ask which inputs would cause a stack overflow in your specific language.
- For tree/graph problems, ask for the traversal order annotated in the trace.
Frequently asked questions
Will recursion hit stack limits?
Ask for the recursion-depth analysis explicitly — the prompt requests it, and the response includes an honest limit plus the iterative fallback.
When should I avoid recursion entirely?
For very deep or unbounded inputs, and in languages without tail-call optimization. The prompt's iterative alternative covers those cases — ask when each wins.