fork(1) download
  1. // Exponentiation operator.
  2.  
  3. import Foundation
  4.  
  5. precedencegroup ExponentiationPrecedence {
  6. associativity: right
  7. higherThan: MultiplicationPrecedence
  8. }
  9.  
  10. infix operator ** : ExponentiationPrecedence
  11.  
  12. func ** <T: BinaryFloatingPoint>(_ x: T, _ y: T) -> Double {
  13. return pow(Double(x), Double(y))
  14. }
  15.  
  16. func ** <T: BinaryInteger>(_ x: T, _ y: T) -> Int {
  17. return Int(pow(Double(x), Double(y)))
  18. }
  19.  
  20. // Test.
  21.  
  22. func check<T: Equatable>(_ f: () -> Any, _ expect: T) {
  23. let result = f()
  24. print(result, terminator: "\t")
  25. if let x = result as? T {
  26. if x == expect {
  27. print("Pass.")
  28. } else {
  29. print("Fail:", expect)
  30. }
  31. } else {
  32. let u = type(of: result)
  33. print("Fail:", u, "not", T.self)
  34. }
  35. }
  36.  
  37. check({2 ** 0}, 1)
  38. check({2 ** Int8(1)}, 2)
  39. check({2.0 ** 2}, 4.0)
  40. check({2.0 ** Float(3)}, 8.0)
  41. check({2 ** 4.0}, 16.0)
  42. check({2.0 ** 5.0}, 32.0)
  43. check({2 * 2 ** 4 * 2}, 64)
Success #stdin #stdout 0.03s 21092KB
stdin
Standard input is empty
stdout
1	Pass.
2	Pass.
4.0	Pass.
8.0	Pass.
16.0	Pass.
32.0	Pass.
64	Pass.