package pzs object Pz012 extends App { case class RomanNumeral(symbol: String, value: Int) implicit object RomanOrdering extends Ordering[RomanNumeral] { def compare(a: RomanNumeral, b: RomanNumeral) = a.value compare b.value } import collection.immutable.SortedSet val numerals = SortedSet(RomanNumeral("M", 1000), RomanNumeral("C", 100), RomanNumeral("X", 10), RomanNumeral("I", 1), RomanNumeral("D", 500), RomanNumeral("L", 50), RomanNumeral("V", 5)) println("Roman numeral symbols for 1 5 10 50 100 500 1000:") for (num <- numerals; sym = num.symbol) { print(s"${sym} ") } println() numerals map { _.symbol } foreach { sym => print(s"${sym} ") } }
解释:
SortedSet中的元素,本来就是有顺序的。RomanNumeral的排序规则是按它的value的大小,字符串的排序规则是按照字典顺序
numerals map { _.symbol } // 已经是一个字符串的有序集合了
Since RomanNumerals are ordered by their values, iterating over the sorted set of numerals will return them in that order and result in the representations being printed according to the value.
Mapping the numerals to their symbols will result in a sorted set of Strings which, naturally enough, will be ordered lexicographically. Iterating over them will thus return them in that order.
时间: 2024-10-13 02:34:53