robdashnash robdashnash - 24 days ago 9
Swift Question

Regarding functions, the math symbol function * is called differently. Why?

The definition of the multiply symbol is this.

public func *(lhs: Int, rhs: Int) -> Int


I can use it in a function, like this.

func productUsingReduce(xs: [Int]) -> Int {
return xs.reduce(1, { x,y in x * y})
}


or simply like this.

func productUsingReduce(xs: [Int]) -> Int {
return xs.reduce(1, *)
}


If I try to define the same thing with a different name.

func yes(lhs: Int, rhs: Int) -> Int {
return lhs * rhs
}


I get a compiler error when I try to use it like this.

func productUsingReduce(xs: [Int]) -> Int {
return xs.reduce(1, { x,y in x yes y})
}


Why?

And why doesn't the following sytnax compile?

func productUsingReduce(xs: [Int]) -> Int {
return xs.reduce(1, { x, y in *(lhs: x, rhs: y) })
}

Answer

* definition is made of two parts:

The method definition (in Swift.Math.Integers, Swift.Math.Floating and so on)

public func *(lhs: Int, rhs: Int) -> Int

and its operator behavior (in Swift, you can write import Swift in Xcode and CMD+click on it to access the file)

infix operator * : MultiplicationPrecedence

The last snippet makes * an infix operator, so you can only use it in infix form.


About your yes function, you cannot make it behave as an operator. While you can define your own custom operators, they can only contain certain characters. As per the language specification:

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.

So you have to use it its standard function form.

But you could do

func ^^^(lhs: Int, rhs: Int) -> Int {
  return lhs * rhs
}

infix operator ^^^

and that would work as expected

3 ^^^ 2 // 6
Comments