我最近在Java中遇到了这段代码.它涉及功能和印刷斐波那契数字,它的工作原理.
public class AppLambdaSubstitution {
public static Function<Integer, Integer> Y(Function<Function<Integer, Integer>, Function<Integer, Integer>> f) {
return x -> f.apply(Y(f)).apply(x);
}
public static void main(String[] args) {
Function<Integer, Integer> fib = Y(
func -> x -> {
if (x < 2)
return x;
else
return func.apply(x - 1) + func.apply(x - 2);
});
IntStream.range(1,11).
mapToObj(Integer::valueOf).
map(fib).forEach(System.out::println);
}
}
Run Code Online (Sandbox Code Playgroud)
困惑的部分是return x -> f.apply(Y(f)).apply(x);.是不是Y(f)递归调用该方法Y?我们一直以函数f作为参数来调用它.对我来说,这种递归调用没有基本情况.为什么无休止的递归调用没有溢出?
我最近开始研究由firebase提供支持的iOS应用程序.我想知道使用firebase的特殊位置/.info/connected是否是检测用户是否有互联网连接的好方法.我知道这通常是使用apple提供的可达性apis来完成的.以下是我的想法:在app委托中,我将设置这样的东西
func application(application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [NSObject: AnyObject]?) -> Bool {
//Configure some stuff
let connectedRef =
Firebase(url:"https://serengeti.firebaseio.com/.info/connected")
connectedRef.observeEventType(.Value, withBlock: { snapshot in
let connected = snapshot.value as? Bool
let userDefaults = NSUserDefaults.standardUserDefaults()
if connected != nil && connected! {
//User is connected
userDefaults.setBool(true, forKey: "connected")
} else {
//User not connected
userDefaults.setBool(false, forKey: "connected")
}
userDefaults.synchronize() //Force value into NSUserDefaults
}
Run Code Online (Sandbox Code Playgroud)
然后在我需要检查连接的功能中(例如,当他们点击facebook注册按钮时)我查找NSUserDefaults条目
func authWithFacebook() {
let userDefaults = NSUserDefaults.standardUserDefaults()
if userDefaults.boolForKey("connected") == false {
//Segue …Run Code Online (Sandbox Code Playgroud)