我如何使用它们的和对一列坐标(x,y)排序

问题描述 投票:-2回答:1

如何在Racket / Scheme博士中使用它们的总和对坐标(x,y)列表进行排序

(sort-points (list (list 2 1) (list 0 0)
(list 0 3) (list -2 4))
=> (list (list 0 0) (list -2 4) (list 0 3) (list 2 1))
racket
1个回答
0
投票

您可以将比较器传递到sort中,告诉它如何对列表中的元素进行排序。

sort

编辑1:不包含lambda:

#lang racket

(sort (list (list 2 1) (list 0 0) (list 0 3) (list -2 4))
      (λ (x y) ; less-than?
        (<= (+ (first x) (second x))
            (+ (first y) (second y)))))
; => '((0 0) (-2 4) (0 3) (2 1))

Edit 2:通过修改您在#lang racket (define (my-sort l) (define (cmp x y) (<= (+ (first x) (second x)) (+ (first y) (second y)))) (sort l cmp)) (my-sort (list (list 2 1) (list 0 0) (list 0 3) (list -2 4))) ; => '((0 0) (-2 4) (0 3) (2 1)) 注释中提供的代码:

this
© www.soinside.com 2019 - 2024. All rights reserved.