-1

why can I write (in swift)

func β(a: Double, b: Double) -> Double { exp( lgamma(a) + lgamma(b) - lgamma(a + b) ) }

or

func Γ(_ x: Double) -> Double { tgamma(x) }

but not

func √(_ x: Double) -> Double { return sqrt(x) }
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
user3585825
  • 27
  • 1
  • 1
  • 3

2 Answers2

4

See Identifiers in the Swift Language Reference:

Identifiers begin with an uppercase or lowercase letter A through Z, an underscore (_), a noncombining alphanumeric Unicode character in the Basic Multilingual Plane, or a character outside the Basic Multilingual Plane that isn’t in a Private Use Area. After the first character, digits and combining Unicode characters are also allowed.

β and Γ are each a "noncombining alphanumeric Unicode character in the Basic Multilingual Plane." √ is not (nor does it meet any of the other requirements).

That said, √ is a valid operator, so you can write:

prefix operator √
prefix func √(_ x: Double) -> Double { return sqrt(x) }
print(√2)

The basic rules for Operators (from the document above) are:

Custom operators can begin with one of the ASCII characters /, =, -, +, !, *, %, <, >, &, |, ^, ?, or ~, or one of the Unicode characters defined in the grammar below (which include characters from the Mathematical Operators, Miscellaneous Symbols, and Dingbats Unicode blocks, among others). After the first character, combining Unicode characters are also allowed.

√ is included in "Mathematical Operators."

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
0

The square root character appears to be a valid operation identifier in Swift.

Character Unicode Value Unicode Name
221A SQUARE ROOT

Have you checked the last method declaration without the return keyword?

func √(_ x: Double) -> Double { sqrt(x) }
D M
  • 5,769
  • 4
  • 12
  • 27
  • 4
    return keyword is optional in single line closures. Your method would throw an error as well **Unary operator implementation must have a 'prefix' or 'postfix' modifier** – Leo Dabus Jan 12 '21 at 15:57
  • Thanks for the clarification. – D M Jan 12 '21 at 16:06