You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. It's fully deterministic: The output depends entirely on the input parameter n. Call fib(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.
  2. No observable side effects: While the function modifies local variables like k, curr, and pred during 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:30:56