我有list-of-cars
,這是car
類型的結構列表,其中包含字段「maker」,「model」和「year」。使用常規球拍sort
功能,我可以通過一個鍵(例如「製造商」)進行排序。但是,我怎麼能通過製造商和型號進行排序,並在例子中列出一個等於輸出sort-by-maker-and-model
的列表?通過多個鍵對球拍中的結構列表進行排序
這不是一個學校的任務,我試圖做一個清晰的例子,比我需要處理的實際數據更枯燥。昂貴的汽車對我來說似乎不算太無聊。
享受我狡猾的例子!祝你今天愉快!
#lang racket/base
(define-struct car (maker model year) #:transparent)
(define list-of-cars (list (car "Ferrari" "250 Europa GT" "1954")
(car "Bugatti" "Type 2" "1900")
(car "Lamborghini" "Flying Star II" "1966")
(car "Bugatti" "Type 10" "1908")
(car "Ferrari" "166 Inter" "1949")
(car "Bugatti" "Type 5" "1903")
(car "Maserati" "A6 1500" "1946")
(car "Ferrari" "340 America" "1951")
(car "Maserati" "5000 GT" "1959")
(car "Maserati" "Quattroporte" "1963")
(car "Lamborghini" "Egoista" "2013")))
(define (sort-by-maker lst)
(sort lst
string<?
#:key car-maker))
(sort-by-maker list-of-cars)
; =>
(list
(car "Bugatti" "Type 2" "1900")
(car "Bugatti" "Type 10" "1908")
(car "Bugatti" "Type 5" "1903")
(car "Ferrari" "250 Europa GT" "1954")
(car "Ferrari" "166 Inter" "1949")
(car "Ferrari" "340 America" "1951")
(car "Lamborghini" "Flying Star II" "1966")
(car "Lamborghini" "Egoista" "2013")
(car "Maserati" "A6 1500" "1946")
(car "Maserati" "5000 GT" "1959")
(car "Maserati" "Quattroporte" "1963"))
(define (sort-by-maker-and-model lst)
; ???
#f)
(sort-by-maker-and-model list-of-cars)
; =>
(list
(car "Bugatti" "Type 2" "1900")
(car "Bugatti" "Type 5" "1903")
(car "Bugatti" "Type 10" "1908")
(car "Ferrari" "166 Inter" "1949")
(car "Ferrari" "250 Europa GT" "1954")
(car "Ferrari" "340 America" "1951")
(car "Lamborghini" "Egoista" "2013")
(car "Lamborghini" "Flying Star II" "1966")
(car "Maserati" "5000 GT" "1959")
(car "Maserati" "A6 1500" "1946")
(car "Maserati" "Quattroporte" "1963"))
隨着一些嘟嘟聲之後,使用'car'作爲結構在這個例子中的名字是一個可怕的想法......即使它起作用,它也重新定義了該語言的普通汽車功能。但無論... – Vasily