Created
January 8, 2016 07:11
-
-
Save harlanhaskins/bafab4a56c445d078ed9 to your computer and use it in GitHub Desktop.
Loops implemented terribly, in Swift
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
func while_(@autoclosure(escaping) cond: () -> Bool, body: () -> ()) { | |
func goto(label: String) { | |
switch label { | |
case "cond": goto(cond() ? "body" : "end") | |
case "body": | |
body() | |
goto("cond") | |
case "end": | |
fallthrough | |
default: break | |
} | |
} | |
goto("cond") | |
} | |
func for_(value: Int, _ cond: Int -> Bool, _ post: (inout Int) -> (), _ body: Int -> ()) { | |
var value = value | |
while_(cond(value)) { | |
body(value) | |
post(&value) | |
} | |
} | |
var j = 100 | |
while_ (j > 50) { | |
print(j) | |
j -= 1 | |
} | |
for_(0, { $0 < 50 }, { $0 += 1 }) { | |
print($0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment