Created
March 4, 2016 23:43
-
-
Save shashir/831cdae0c371f0724e32 to your computer and use it in GitHub Desktop.
argmin and argmax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object ArgMinMax { | |
import scala.reflect.ClassTag | |
def argmin[X: ClassTag, Y <% Ordered[Y] : ClassTag](n: Iterable[X], f: X => Y): X = { | |
val (argmin: X, min: Y) = n.tail.fold((n.head, f(n.head))) { case ((a: X, m: Y), x: X) => | |
val fOfx: Y = f(x) | |
if (fOfx < m) (x, fOfx) else (a, m) | |
} | |
return argmin | |
} | |
def argmax[X: ClassTag, Y <% Ordered[Y] : ClassTag](n: Iterable[X], f: X => Y): X = { | |
val (argmin: X, min: Y) = n.tail.fold((n.head, f(n.head))) { case ((a: X, m: Y), x: X) => | |
val fOfx: Y = f(x) | |
if (fOfx > m) (x, fOfx) else (a, m) | |
} | |
return argmin | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment