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 testBase:Double = 0.9

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

func main() -> Void {
	for p:Int in stride(from: 10, through: -1, by: -1) {
		print(Utils.format("{0:f} ^ {1:d} = {2:f}", testBase, p, exponentiation(testBase, p)))
	}
	exit(EXIT_SUCCESS)
}
main()

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 testBase: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.0
	while power > 0 {
		result *= base
		power -= 1
	}
	return result
}

func main() -> Void {
	for p:Int in stride(from: 10, through: -1, by: -1) {
		print(Utils.format("{0:f} ^ {1:d} = {2:f}", testBase, p, exponentiation(testBase, p)))
	}
	exit(EXIT_SUCCESS)
}
main()

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 testBase: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.0
	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.0) ? result < 0.0 : result >= 0.0, "Postcondition Failed: Result is wrong sign")
	return result
}

func main() -> Void {
	for p:Int in stride(from: 10, through: -1, by: -1) {
		print(Utils.format("{0:f} ^ {1:d} = {2:f}", testBase, p, exponentiation(testBase, p)))
	}
	exit(EXIT_SUCCESS)
}
main()

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