> Sum of Fibonacci term using Functional Swift
问题:我们如何使用现代Swift(Swift> = 3)整齐地生成斐波纳契数?优选地,避免显式递归的方法.
Swift 3.0的另一种选择是使用辅助函数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)}
从Express for loops in swift with dynamic range:
for f in sequence(first: (0,1),while: { <= 50 },next: { (,for f in sequence(first: (1,0),+ )}) { print(f.1)}// 1 1 2 3 5 8 13 21 34if pair.1 == 0 { pair.1 = 1; return 0 }+ )}) { print(f.1)}// 0 1 1 2 3 5 8 13 21 34
请注意,为了在结果序列中包含零,它
足以用(1,0)替换初始值(0,1):
... -8,5,-3,2,-1,1,3,8,...
这使得“人为”检查
多余的.根本原因是Fibonacci数字可以
推广到负指数(https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers):
以上是内存溢出为你收集整理的Swift 3中的Fibonacci数字生成器全部内容,希望文章能够帮你解决Swift 3中的Fibonacci数字生成器所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)