Swift 3 中的斐波那契数列生成器 [英] Fibonacci numbers generator in Swift 3

查看:13
本文介绍了Swift 3 中的斐波那契数列生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下问答涵盖了在 Swift 中生成斐波那契数列的几种方法,但它已经过时了(Swift 1.2?):

The following Q&A covers a few methods of generating Fibonacci numbers in Swift, but it's quite outdated (Swift 1.2?):

问题:我们如何使用现代 Swift (Swift >= 3) 巧妙地生成斐波那契数列?最好是避免显式递归的方法.

Question: How could we generate Fibonacci numbers neatly using modern Swift (Swift >= 3)? Preferably methods avoiding explicit recursion.

推荐答案

Swift 3.0 的另一种选择是使用辅助函数

An alternative for Swift 3.0 would be to use the helper function

public func sequence<T>(first: T, while condition: @escaping (T)-> Bool, next: @escaping (T) -> T) -> UnfoldSequence<T, T> {
    let nextState = { (state: inout T) -> T? in
        // Return `nil` if condition is no longer satisfied:
        guard condition(state) else { return nil }
        // Update current value _after_ returning from this call:
        defer { state = next(state) }
        // Return current value:
        return state
    }
    return sequence(state: first, next: nextState)
}

来自 快速表达具有动态范围的循环:

for f in sequence(first: (0, 1), while: { $1 <= 50 }, next: { ($1, $0 + $1)}) {
    print(f.1)
}
// 1 1 2 3 5 8 13 21 34

请注意,为了在结果序列中包含零,它将初始值 (0, 1) 替换为 (1, 0) 即可:

Note that in order to include zero in the resulting sequence, it suffices to replace the initial value (0, 1) by (1, 0):

for f in sequence(first: (1, 0), while: { $1 <= 50 }, next: { ($1, $0 + $1)}) {
    print(f.1)
}
// 0 1 1 2 3 5 8 13 21 34

这使得人工"检查

if pair.1 == 0 { pair.1 = 1; return 0 }

冗余.根本原因是斐波那契数列可以推广到负指数(https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers):

redundant. The underlying reason is that the Fibonacci numbers can be generalized to negative indices (https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers):

 ... -8, 5, -3, 2, -1, 1, 0, 1, 1, 2, 3, 5, 8, ...

这篇关于Swift 3 中的斐波那契数列生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆