-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add acceptance/performance test with a program that calculates Fibonn…
…aci numbers.
- Loading branch information
Dan Cutting
committed
Mar 9, 2018
1 parent
617ebb4
commit 865005f
Showing
3 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import XCTest | ||
import Song | ||
|
||
class FibonacciTests: XCTestCase { | ||
|
||
func test() { | ||
let code = """ | ||
n.fib = n.fib(0, 1) | ||
0.fib(a, _) = a | ||
n.fib(a, b) When n > 0 = (n-1).fib(b, a+b) | ||
80.fib | ||
""" | ||
measure { | ||
assertNoThrow { | ||
XCTAssertEqual(Expression.int(23416728348467685), try evaluate(code)) | ||
} | ||
} | ||
} | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import XCTest | ||
import Song | ||
|
||
func assertNoThrow(file: StaticString = #file, line: UInt = #line, _ closure: () throws -> Void) { | ||
do { | ||
try closure() | ||
} catch { | ||
XCTFail("\(error)", file: file, line: line) | ||
} | ||
} | ||
|
||
func evaluate(_ code: String) throws -> Expression? { | ||
let parser = makeParser() | ||
let transformer = makeTransformer() | ||
let lines = code.split(separator: "\n") | ||
var context = Context() | ||
var lastEval: Expression? | ||
for line in lines { | ||
let result = parser.parse(String(line)) | ||
let expression = try transformer.transform(result) | ||
let evaluated = try expression.evaluate(context: context) | ||
if case .closure(let name, _, _) = evaluated { | ||
if let name = name { | ||
context = extendContext(context: context, name: name, value: evaluated) | ||
} | ||
} | ||
if case .assign(let variable, let value) = evaluated { | ||
if case .name(let name) = variable { | ||
context = extendContext(context: context, name: name, value: value) | ||
} | ||
} | ||
lastEval = evaluated | ||
} | ||
return lastEval | ||
} |