Write a generic mostFrequent function with a where-style constraint and explain each constraint.
Implement a generic mostFrequent that returns the most common element of an array, or nil for an empty array.
Requirements:
- Signature:
func mostFrequent<T: Hashable>(_ xs: [T]) -> T?. - Count occurrences with a dictionary, then return the element with the highest count.
- Explain why the constraint and the optional return are needed.
func mostFrequent<T: Hashable>(_ xs: [T]) -> T? {
// your code here
}
Write the implementation.
func mostFrequent<T: Hashable>(_ xs: [T]) -> T? — the Hashable bound lets T be a dictionary key to tally counts, and T? is returned because empty input has no mode. A where clause adds constraints like T: Comparable to break ties.
- ✗Dropping the
Hashableconstraint while still usingTas a dictionary key - ✗Returning a non-optional
Teven though an empty input has no mode - ✗Thinking a
whereclause is illegal on a free function
- →Why does using
Tas a dictionary key forceT: Hashable? - →How would
T: Comparablehelp break a frequency tie?
Count into a dictionary, then take the key with the largest count:
func mostFrequent<T: Hashable>(_ xs: [T]) -> T? {
var counts: [T: Int] = [:]
for x in xs { counts[x, default: 0] += 1 }
return counts.max { $0.value < $1.value }?.key
}
T: Hashable is required because T is used as a dictionary key, and dictionaries hash their keys. The return is T? because an empty array has no most-frequent element — max(by:) returns an optional pair and ?.key propagates the nil. Adding where T: Comparable would let you break ties deterministically instead of picking an arbitrary winner.