Pure Programmer
Blue Matrix


Cluster Map

Assertions

L1

This page is under construction. Please come back later.

Assertions1.swift
#!/usr/bin/env swift;
import Foundation
import Utils

let TEST_BASE:Double = 0.9

func exponentiation(_ base:Double, _ powerArg:Int) -> Double {
	assert(powerArg >= 0, "powerArg >= 0")
	var power:Int = powerArg
	var result:Double = 1
	while power > 0 {
		result *= base
		power -= 1
	}
	return result
}

// Begin Main
for p:Int in stride(from: 10, through: -1, by: -1) {
	print(Utils.format("{0:f} ^ {1:d} = {2:f}", TEST_BASE, p, exponentiation(TEST_BASE, p)))
}

exit(EXIT_SUCCESS)

Output
$ swiftc Assertions1.swift -I . -L . -lUtils error: link command failed with exit code 1 (use -v to see invocation) ld: library not found for -lUtils clang: error: linker command failed with exit code 1 (use -v to see invocation)
Assertions2.swift
#!/usr/bin/env swift;
import Foundation
import Utils

let TEST_BASE:Double = 0.9

func exponentiation(_ base:Double, _ powerArg:Int) -> Double {
	assert(powerArg >= 0, "exponentiation() power must be non-negative, was " + String(powerArg))
	var power:Int = powerArg
	var result:Double = 1
	while power > 0 {
		result *= base
		power -= 1
	}
	return result
}

// Begin Main
for p:Int in stride(from: 10, through: -1, by: -1) {
	print(Utils.format("{0:f} ^ {1:d} = {2:f}", TEST_BASE, p, exponentiation(TEST_BASE, p)))
}

exit(EXIT_SUCCESS)

Output
$ swiftc Assertions2.swift -I . -L . -lUtils error: link command failed with exit code 1 (use -v to see invocation) ld: library not found for -lUtils clang: error: linker command failed with exit code 1 (use -v to see invocation)
Assertions3.swift
#!/usr/bin/env swift;
import Foundation
import Utils

let TEST_BASE:Double = 0.9

func exponentiation(_ base:Double, _ powerArg:Int) -> Double {
	assert(powerArg >= 0, "exponentiation() power must be non-negative, was " + String(powerArg))
	var power:Int = powerArg
	var result:Double = 1
	while power > 0 {
		result *= base
		power -= 1
	}
// This line will make the result incorrect.
	result = -result
// If power is odd and base is negative, then result should be negative.
// Otherwise result should be positive.
	assert((power & 1) == 1 && (base < 0) ? result < 0 : result >= 0, "Postcondition Failed: Result is wrong sign")
	return result
}

// Begin Main
for p:Int in stride(from: 10, through: -1, by: -1) {
	print(Utils.format("{0:f} ^ {1:d} = {2:f}", TEST_BASE, p, exponentiation(TEST_BASE, p)))
}

exit(EXIT_SUCCESS)

Output
$ swiftc Assertions3.swift -I . -L . -lUtils error: link command failed with exit code 1 (use -v to see invocation) ld: library not found for -lUtils clang: error: linker command failed with exit code 1 (use -v to see invocation)
swift

Questions

Projects

More ★'s indicate higher difficulty level.

References