gopl-zh.github.com/ch7/ch7-06.md

220 lines
12 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

## 7.6. sort.Interface接口
排序操作和字符串格式化一樣是很多程序經常使用的操作。盡管一個最短的快排程序隻要15行就可以搞定但是一個健壯的實現需要更多的代碼併且我們不希望每次我們需要的時候都重寫或者拷貝這些代碼。
幸運的是sort包內置的提供了根據一些排序函數來對任何序列排序的功能。它的設計非常獨到。在很多語言中排序算法都是和序列數據類型關聯同時排序函數和具體類型元素關聯。相比之下Go語言的sort.Sort函數不會對具體的序列和它的元素做任何假設。相反它使用了一個接口類型sort.Interface來指定通用的排序算法和可能被排序到的序列類型之間的約定。這個接口的實現由序列的具體表示和它希望排序的元素決定序列的表示經常是一個切片。
一個內置的排序算法需要知道三個東西序列的長度表示兩個元素比較的結果一種交換兩個元素的方式這就是sort.Interface的三個方法
```go
package sort
type Interface interface {
Len() int
Less(i, j int) bool // i, j are indices of sequence elements
Swap(i, j int)
}
```
爲了對序列進行排序我們需要定義一個實現了這三個方法的類型然後對這個類型的一個實例應用sort.Sort函數。思考對一個字符串切片進行排序這可能是最簡單的例子了。下面是這個新的類型StringSlice和它的LenLess和Swap方法
```go
type StringSlice []string
func (p StringSlice) Len() int { return len(p) }
func (p StringSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p StringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
```
現在我們可以通過像下面這樣將一個切片轉換爲一個StringSlice類型來進行排序
```go
sort.Sort(StringSlice(names))
```
這個轉換得到一個相同長度容量和基於names數組的切片值併且這個切片值的類型有三個排序需要的方法。
對字符串切片的排序是很常用的需要所以sort包提供了StringSlice類型也提供了Strings函數能讓上面這些調用簡化成sort.Strings(names)。
這里用到的技術很容易適用到其它排序序列中例如我們可以忽略大些或者含有特殊的字符。本書使用Go程序對索引詞和頁碼進行排序也用到了這個技術對羅馬數字做了額外邏輯處理。對於更複雜的排序我們使用相同的方法但是會用更複雜的數據結構和更複雜地實現sort.Interface的方法。
我們會運行上面的例子來對一個表格中的音樂播放列表進行排序。每個track都是單獨的一行每一列都是這個track的屬性像藝術家標題和運行時間。想象一個圖形用戶界面來呈現這個表格併且點擊一個屬性的頂部會使這個列表按照這個屬性進行排序再一次點擊相同屬性的頂部會進行逆向排序。讓我們看下每個點擊會發生什麽響應。
下面的變量tracks包好了一個播放列表。One of the authors apologizes for the other authors musical tastes.每個元素都不是Track本身而是指向它的指針。盡管我們在下面的代碼中直接存儲Tracks也可以工作sort函數會交換很多對元素所以如果每個元素都是指針會更快而不是全部Track類型指針是一個機器字碼長度而Track類型可能是八個或更多。
```go
//gopl.io/ch7/sorting
type Track struct {
Title string
Artist string
Album string
Year int
Length time.Duration
}
var tracks = []*Track{
{"Go", "Delilah", "From the Roots Up", 2012, length("3m38s")},
{"Go", "Moby", "Moby", 1992, length("3m37s")},
{"Go Ahead", "Alicia Keys", "As I Am", 2007, length("4m36s")},
{"Ready 2 Go", "Martin Solveig", "Smash", 2011, length("4m24s")},
}
func length(s string) time.Duration {
d, err := time.ParseDuration(s)
if err != nil {
panic(s)
}
return d
}
```
printTracks函數將播放列表打印成一個表格。一個圖形化的展示可能會更好點但是這個小程序使用text/tabwriter包來生成一個列是整齊對齊和隔開的表格像下面展示的這樣。註意到*tabwriter.Writer是滿足io.Writer接口的。它會收集每一片寫向它的數據它的Flush方法會格式化整個表格併且將它寫向os.Stdout標準輸出
```go
func printTracks(tracks []*Track) {
const format = "%v\t%v\t%v\t%v\t%v\t\n"
tw := new(tabwriter.Writer).Init(os.Stdout, 0, 8, 2, ' ', 0)
fmt.Fprintf(tw, format, "Title", "Artist", "Album", "Year", "Length")
fmt.Fprintf(tw, format, "-----", "------", "-----", "----", "------")
for _, t := range tracks {
fmt.Fprintf(tw, format, t.Title, t.Artist, t.Album, t.Year, t.Length)
}
tw.Flush() // calculate column widths and print table
}
```
爲了能按照Artist字段對播放列表進行排序我們會像對StringSlice那樣定義一個新的帶有必須LenLess和Swap方法的切片類型。
```go
type byArtist []*Track
func (x byArtist) Len() int { return len(x) }
func (x byArtist) Less(i, j int) bool { return x[i].Artist < x[j].Artist }
func (x byArtist) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
```
爲了調用通用的排序程序我們必須先將tracks轉換爲新的byArtist類型它定義了具體的排序
```go
sort.Sort(byArtist(tracks))
```
在按照artist對這個切片進行排序後printTrack的輸出如下
```
Title Artist Album Year Length
----- ------ ----- ---- ------
Go Ahead Alicia Keys As I Am 2007 4m36s
Go Delilah From the Roots Up 2012 3m38s
Ready 2 Go Martin Solveig Smash 2011 4m24s
Go Moby Moby 1992 3m37s
```
如果用戶第二次請求“按照artist排序”我們會對tracks進行逆向排序。然而我們不需要定義一個有顛倒Less方法的新類型byReverseArtist因爲sort包中提供了Reverse函數將排序順序轉換成逆序。
```go
sort.Sort(sort.Reverse(byArtist(tracks)))
```
在按照artist對這個切片進行逆向排序後printTrack的輸出如下
```
Title Artist Album Year Length
----- ------ ----- ---- ------
Go Moby Moby 1992 3m37s
Ready 2 Go Martin Solveig Smash 2011 4m24s
Go Delilah From the Roots Up 2012 3m38s
Go Ahead Alicia Keys As I Am 2007 4m36s
```
sort.Reverse函數值得進行更近一步的學習因爲它使用了(§6.3)章中的組合這是一個重要的思路。sort包定義了一個不公開的struct類型reverse它嵌入了一個sort.Interface。reverse的Less方法調用了內嵌的sort.Interface值的Less方法但是通過交換索引的方式使排序結果變成逆序。
```go
package sort
type reverse struct{ Interface } // that is, sort.Interface
func (r reverse) Less(i, j int) bool { return r.Interface.Less(j, i) }
func Reverse(data Interface) Interface { return reverse{data} }
```
reverse的另外兩個方法Len和Swap隱式地由原有內嵌的sort.Interface提供。因爲reverse是一個不公開的類型所以導出函數Reverse函數返迴一個包含原有sort.Interface值的reverse類型實例。
爲了可以按照不同的列進行排序我們必須定義一個新的類型例如byYear
```go
type byYear []*Track
func (x byYear) Len() int { return len(x) }
func (x byYear) Less(i, j int) bool { return x[i].Year < x[j].Year }
func (x byYear) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
```
在使用sort.Sort(byYear(tracks))按照年對tracks進行排序後printTrack展示了一個按時間先後順序的列表
```
Title Artist Album Year Length
----- ------ ----- ---- ------
Go Moby Moby 1992 3m37s
Go Ahead Alicia Keys As I Am 2007 4m36s
Ready 2 Go Martin Solveig Smash 2011 4m24s
Go Delilah From the Roots Up 2012 3m38s
```
對於我們需要的每個切片元素類型和每個排序函數我們需要定義一個新的sort.Interface實現。如你所見Len和Swap方法對於所有的切片類型都有相同的定義。下個例子具體的類型customSort會將一個切片和函數結合使我們隻需要寫比較函數就可以定義一個新的排序。順便説下實現了sort.Interface的具體類型不一定是切片類型customSort是一個結構體類型。
```go
type customSort struct {
t []*Track
less func(x, y *Track) bool
}
func (x customSort) Len() int
func (x customSort) Less(i, j int) bool { return x.less(x.t[i], x.t[j]) }
func (x customSort) Swap(i, j int) { x.t[i], x.t[j] = x.t[j], x.t[i] }
```
讓我們定義一個多層的排序函數它主要的排序鍵是標題第二個鍵是年第三個鍵是運行時間Length。下面是該排序的調用其中這個排序使用了匿名排序函數
```go
sort.Sort(customSort{tracks, func(x, y *Track) bool {
if x.Title != y.Title {
return x.Title < y.Title
}
if x.Year != y.Year {
return x.Year < y.Year
}
if x.Length != y.Length {
return x.Length < y.Length
}
return false
}})
```
這下面是排序的結果。註意到兩個標題是“Go”的track按照標題排序是相同的順序但是在按照year排序上更久的那個track優先。
```
Title Artist Album Year Length
----- ------ ----- ---- ------
Go Moby Moby 1992 3m37s
Go Delilah From the Roots Up 2012 3m38s
Go Ahead Alicia Keys As I Am 2007 4m36s
Ready 2 Go Martin Solveig Smash 2011 4m24s
```
盡管對長度爲n的序列排序需要 O(n log n)次比較操作檢査一個序列是否已經有序至少需要n1次比較。sort包中的IsSorted函數幫我們做這樣的檢査。像sort.Sort一樣它也使用sort.Interface對這個序列和它的排序函數進行抽象但是它從不會調用Swap方法這段代碼示范了IntsAreSorted和Ints函數和IntSlice類型的使用
```go
values := []int{3, 1, 4, 1}
fmt.Println(sort.IntsAreSorted(values)) // "false"
sort.Ints(values)
fmt.Println(values) // "[1 1 3 4]"
fmt.Println(sort.IntsAreSorted(values)) // "true"
sort.Sort(sort.Reverse(sort.IntSlice(values)))
fmt.Println(values) // "[4 3 1 1]"
fmt.Println(sort.IntsAreSorted(values)) // "false"
```
爲了使用方便sort包爲[]int,[]string和[]float64的正常排序提供了特定版本的函數和類型。對於其他類型例如[]int64或者[]uint盡管路徑也很簡單還是依賴我們自己實現。
**練習 7.8** 很多圖形界面提供了一個有狀態的多重排序表格插件主要的排序鍵是最近一次點擊過列頭的列第二個排序鍵是第二最近點擊過列頭的列等等。定義一個sort.Interface的實現用在這樣的表格中。比較這個實現方式和重複使用sort.Stable來排序的方式。
**練習 7.9** 使用html/template包 (§4.6) 替代printTracks將tracks展示成一個HTML表格。將這個解決方案用在前一個練習中讓每次點擊一個列的頭部産生一個HTTP請求來排序這個表格。
**練習 7.10** sort.Interface類型也可以適用在其它地方。編寫一個IsPalindrome(s sort.Interface) bool函數表明序列s是否是迴文序列換句話説反向排序不會改變這個序列。假設如果!s.Less(i, j) && !s.Less(j, i)則索引i和j上的元素相等。