Created
April 24, 2017 12:18
-
-
Save omochi/945fbf77566ab507dd95783f2f64deae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 普通にやるとクロージャーは自己再帰できないよねという話 | |
let fib1 = { (x: Int) -> Int in | |
switch (x) { | |
case 0: | |
return 0 | |
case 1: | |
return 1 | |
default: | |
fatalError("can not implement") | |
//return fib1(x - 2) + fib1(x - 1) | |
} | |
} | |
// fib1(4) | |
// varで一回退避すればできるよね | |
var fib2: ((Int) -> Int)? = nil | |
fib2 = { (x: Int) -> Int in | |
switch (x) { | |
case 0: | |
return 0 | |
case 1: | |
return 1 | |
default: | |
return fib2!(x - 2) + fib2!(x - 1) | |
} | |
} | |
print(fib2!(6)) | |
// でも Optional とか ! とかなって嫌だよね | |
// そんな時におもしろいのが高階関数rec | |
// ↓こんなんを用意しておいて | |
func rec<T, R>(fn: @escaping ((T) -> R, T) -> R) -> (T) -> R { | |
func rf(_ x: T) -> R { | |
return fn(rf, x) | |
} | |
return rf | |
} | |
// ↓こーやると | |
let fib3 = rec { (fib: (Int) -> Int, x: Int) -> Int in | |
switch (x) { | |
case 0: | |
return 0 | |
case 1: | |
return 1 | |
default: | |
return fib(x - 2) + fib(x - 1) | |
} | |
} | |
// わーい | |
print(fib3(6)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment