簡體   English   中英

根據運算符對 Racket 中的列表進行排序

[英]Sort a list in Racket based on the operator

如何根據 Racket-Plait 中的運算符對兩個列表進行排序和合並? > 升序,< 降序。 到目前為止,這是我所擁有的,但我不知道下一步該怎么做。

(define (merge [op : (Number Number -> Boolean)]
               [int-list1 : (Listof Number)]
               [int-list2 : (Listof Number)]) : (Listof Number)
  (cond
    [(equal? op <) "something"]
    [(equal? op >) "do something"])) 

(test (merge < '(1 4 6) '(2 5 8))
      '(1 2 4 5 6 8))

我認為您假設這比實際情況更復雜。

你不應該根據op的值做不同的事情 - op是你應該用於合並的排序謂詞和輸入列表排序的謂詞。
(與許多其他語言相比,像<>這樣的符號在任何方面都不是“特殊的”,它們就像lessgreaterop一樣是標識符)

這是一個可以幫助您入門的骨架特例; 有趣的部分留作練習:

(define (merge [l1 : (Listof Number)]
               [l2 : (Listof Number)]) : (Listof Number)
  (cond [(empty? l1) l2]  ;; If either list is empty,
        [(empty? l2) l1]  ;; the result is the other list.
        [(< (first l1) (first l2)) ... fill this in ...]
        [else ... fill this in ...]))

然后,注意這等同於上面的代碼:

(define op <)

(define (merge [l1 : (Listof Number)]
               [l2 : (Listof Number)]) : (Listof Number)
  (cond [(empty? l1) l2]  ;; If either list is empty,
        [(empty? l2) l1]  ;; the result is the other list.
        [(op (first l1) (first l2)) ... fill this in ...]
        [else ... fill this in ...]))

然后你將op作為參數傳遞,你就完成了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM