Skip to content

[stdlib] Refactor min()/max() #615

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Dec 18, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 24 additions & 21 deletions stdlib/public/core/Algorithm.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,47 +44,50 @@ public func find<
}

/// Returns the lesser of `x` and `y`.
///
/// If `x == y`, returns `x`.
@warn_unused_result
public func min<T : Comparable>(x: T, _ y: T) -> T {
var r = x
if y < x {
r = y
}
return r
// In case `x == y` we pick `x`.
// This preserves any pre-existing order in case `T` has identity,
// which is important for e.g. the stability of sorting algorithms.
// `(min(x, y), max(x, y))` should return `(x, y)` in case `x == y`.
return y < x ? y : x
}

/// Returns the least argument passed.
///
/// If there are multiple equal least arguments, returns the first one.
@warn_unused_result
public func min<T : Comparable>(x: T, _ y: T, _ z: T, _ rest: T...) -> T {
var r = x
if y < x {
r = y
}
if z < r {
r = z
var minValue = min(min(x, y), z)
// In case `value == minValue`, we pick `minValue`. See min(_:_:).
for value in rest where value < minValue {
minValue = value
}
for t in rest {
if t < r {
r = t
}
}
return r
return minValue
}

/// Returns the greater of `x` and `y`.
///
/// If `x == y`, returns `y`.
@warn_unused_result
public func max<T : Comparable>(x: T, _ y: T) -> T {
// In case `x == y`, we pick `y`. See min(_:_:).
return y >= x ? y : x
}

/// Returns the greatest argument passed.
///
/// If there are multiple equal greatest arguments, returns the last one.
@warn_unused_result
public func max<T : Comparable>(x: T, _ y: T, _ z: T, _ rest: T...) -> T {
var r = max(max(x, y), z)
for t in rest where t >= r {
r = t
var maxValue = max(max(x, y), z)
// In case `value == maxValue`, we pick `value`. See min(_:_:).
for value in rest where value >= maxValue {
maxValue = value
}
return r
return maxValue
}

/// Returns the result of slicing `elements` into sub-sequences that
Expand Down