Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using Swift reduce() and min() to find minimum value in an array
struct Value {
let num: Int
init(_ n: Int) { num = n }
}
let a = [Value(3), Value(2), Value(1), Value(4), Value(5)]
let min1: Value = a.reduce(Value(Int.max)) {
($0.num < $1.num) ? $0 : $1
}
println("min1 is \(min1.num)")
// Use the standard library "min" operator
// Have to make Value conform to Comparable
extension Value: Comparable {}
func ==(lhs: Value, rhs: Value) -> Bool {
return lhs.num < rhs.num
}
func <(lhs: Value, rhs: Value) -> Bool {
return lhs.num < rhs.num
}
let min2: Value = a.reduce(Value(Int.max), combine: min)
println("min2 is \(min2.num)")
// Use map and reduce with min
let min3: Int = a.map{ $0.num }.reduce(Int.max, combine: min)
println("min3 is \(min3)")
// Lazy evaluation
let min4: Int = reduce(lazy(a).map{ $0.num }, Int.max, min)
println("min4 is \(min4)")
// Generic function to find minimum element of a sequence of Comparable items
func minElement<T : Comparable, S : SequenceType where S.Generator.Element == T>(sequence: S, initial: T) -> T {
return reduce(sequence, initial, min)
}
let min5 = minElement(a, Value(Int.max))
println("min5 is \(min5)")
// Lexicographical ordering of strings
let minString = minElement(["one", "two", "three", "four"], "~")
println("minString is \"\(minString)\"")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment