Skip to content

Instantly share code, notes, and snippets.

@hiroshi-maybe
Created April 21, 2016 06:45
Show Gist options
  • Select an option

  • Save hiroshi-maybe/7ee030bcadfdcb89bceb87ef24acb994 to your computer and use it in GitHub Desktop.

Select an option

Save hiroshi-maybe/7ee030bcadfdcb89bceb87ef24acb994 to your computer and use it in GitHub Desktop.
Tail Call Optimization test
//
// TCOTests.swift
// Playground
//
// Created by kori on 4/20/16.
// Copyright © 2016 hiroshi.kori. All rights reserved.
//
import XCTest
func simpleRec(n: Int) -> Int {
if n == 0 {
return 0
} else {
return 1 + simpleRec(n-1)
}
}
// vs
func tailRec(n: Int, res: Int = 0) -> Int {
if n == 0 {
return res
} else {
return tailRec(n - 1, res: res + 1)
}
}
class TCOTests: XCTestCase {
let recCount = 1000000
func testTailRec() {
XCTAssertEqual(tailRec(recCount), recCount)
}
func testSimpleRec() {
XCTAssertEqual(simpleRec(recCount), recCount)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment