3

As an exercise in learning Swift, I'm trying to write minimum and maximum functions for arrays, as follows:

extension Array {

  func comparest<C: Comparable>(comparator: T -> C, _ op: (C, C) -> Bool) -> T? {
    var min = self.first
      for elem in self {
          if op(comparator(elem), comparator(min!)) {
            min = elem
          }
      }
      return min
  }                     

  func minimum<C: Comparable>(var _ comparator: (T -> C)? = nil) -> T? {
    if comparator == nil {
          comparator = { elem -> C in elem as C }
      }
      return self.comparest(comparator!, <) 
  }

}

I've left out the maximum function because it's the same as minimum, but with a different operator passed to comparest. I've tested the comparest function and it works well, e.g.

var array = [4, 2, 3]
var min = array.comparest({ $0 }, <)!

The value of min is correctly 2.

My problem is that the compiler does not like my minimum function. It shows an angry red error on the line self.comparest(comparator!, <) and says "Partial application of generic method not allowed." I've written enough Haskell to know what partial application is, but for the life of me this does not look like partial application. All arguments are specified.

Any ideas?

Gregory Higley
  • 15,923
  • 9
  • 67
  • 96

1 Answers1

1

To use an operator as a function, surround it in parens:

var min = array.comparest({ $0 }, (<))!

For example:

[1,2,3].reduce(0,(+)) // -> 6
Alex Brown
  • 41,819
  • 10
  • 94
  • 108