Created
October 12, 2014 15:30
-
-
Save terhechte/a8059c45f259b7a5ba01 to your computer and use it in GitHub Desktop.
Implement "cond" expression (from Lisp) 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
// | |
// AppDelegate.swift | |
// testasdfsadf | |
// | |
// Created by Benedikt Terhechte on 10/12/14. | |
// Copyright (c) 2014 Benedikt Terhechte. All rights reserved. | |
// | |
import Cocoa | |
func _cond<T> (a1: @autoclosure () -> Bool, b1: @autoclosure () -> T?, | |
a2: @autoclosure () -> Bool, b2: @autoclosure () -> T?, | |
a3: @autoclosure () -> Bool, b3: @autoclosure () -> T?, | |
a4: @autoclosure () -> Bool, b4: @autoclosure () -> T?, | |
a5: @autoclosure () -> Bool, b5: @autoclosure () -> T? | |
) -> T? { | |
if a1() { | |
return b1() | |
} else if a2() { | |
return b2() | |
} else if a3() { | |
return b3() | |
} else if a4() { | |
return b4() | |
} else if a5() { | |
return b5() | |
} | |
return nil | |
} | |
// two parameter implementation | |
func cond<T>(a1: @autoclosure () -> Bool, b1: @autoclosure () -> T?, | |
a2: @autoclosure () -> Bool, b2: @autoclosure () -> T?, | |
bf: @autoclosure () -> T?) -> T { | |
if let r = _cond(a1, b1, a2, b2, false, {return nil}(), false, {return nil}(), false, {return nil}()) { | |
return r | |
} | |
return bf()! | |
} | |
@NSApplicationMain | |
class AppDelegate: NSObject, NSApplicationDelegate { | |
@IBOutlet weak var window: NSWindow! | |
func applicationDidFinishLaunching(aNotification: NSNotification) { | |
// Insert code here to initialize your application | |
let value = cond(4 == 5, 8, // if 4 equals 5, return 9 | |
3 == 3, 9, // if 3 equels 3, return 9 | |
10) // else, return 10 | |
print ("Value is", value) | |
} | |
func applicationWillTerminate(aNotification: NSNotification) { | |
// Insert code here to tear down your application | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment