fib(n)是否为纯函数?附其实现代码及特性说明
Is
fib(n) a Pure Function? Absolutely, yes! Let's break this down using the core definitions of a pure function to confirm:
Core Traits of a Pure Function
- Deterministic: For the exact same input, it will always return the exact same output—no randomness, no dependency on external state that could shift between calls.
- No Observable Side Effects: It doesn't modify anything outside its own scope, perform I/O operations, or leave any lasting changes that other parts of the program can detect.
Applying These Rules to Your fib(n) Implementation
Let's walk through your code:
- It's fully deterministic: The output depends entirely on the input parameter
n. Callfib(7)once, twice, or a hundred times, and you'll always get 13 (since the 7th Fibonacci number here is 13, with the 0th defined as 0). There's no reliance on global variables, timers, or any external value that could change between executions. - No observable side effects: While the function modifies local variables like
k,curr, andpredduring its loop, these variables are strictly contained within the function's scope. Once the function finishes running, they're discarded entirely—they don't alter any global state, data structures, or other parts of the program. The problem statement even explicitly notes it has no side effects on other code and is thread-safe, which lines up perfectly with pure function behavior.
The internal mutable state (the local variables) doesn't disqualify it. Pure functions can have temporary internal state changes as long as those changes never escape the function and don't impact future calls with the same input.
内容的提问来源于stack exchange,提问作者overexchange
相关产品推荐
相关产品推荐

