简体   繁体   English

使用排序与球拍中的键排序功能列表

[英]Sort list of function using sort with key in racket

(functionsort functionlist value)

functionsort takes 2 argument, list of functions and a single value. functionsort采用2个参数,函数列表和单个值。 return same list of function sorted in increasing order when given "value". 当给定“value”时,返回以递增顺序排序的相同函数列表。

for example : here is my list of function 例如:这是我的功能列表

(define myfunctions (list (lambda (x) (+ x 3)) 
                     (lambda (x) (- 100 x))
                     (lambda (x) (* x 2))))
(define fs 
    (function-sort myfunctions
                   5))

should return the following 应该返回以下内容

((first fs) 6)   ; (first fs) is (lambda (x) (+ x 3))
9
((second fs) 6)  ; (second fs) is (lambda (x) (* x 2))
12
((third fs) 6)   ; (third fs) is (lambda (x) (- 100 x))   
94

here is what i got so far: 这是我到目前为止所得到的:

define (function-sort functions value )
   (map (lambda (y) (y value)) functions))

which compute the value , 9 94 12 un sorted. 计算值,9 94 12 un sorted。 and I try to use 我试着用

 (sort myfunctions #:key (function-sort myfunctions 10) <)

which gives me error 这给了我错误

. . sort: contract violation
expected: (any/c . -> . any/c)
given: '(13 90 20).

Any suggestion ? 有什么建议吗? thanks in advance 提前致谢

Your attempt was on the right track, but you have to pass an adequate argument for #:key - we want to evaluate each function with the given value, and the sort procedure will sort the input list of functions according to the result returned by each function, when applied to the value. 你的尝试是在正确的轨道上,但是你必须为#:key传递足够的参数 - 我们想用给定的值来评估每个函数,并且sort过程将根据每个函数返回的结果对函数的输入列表进行排序。函数,应用于值时。 Try this: 试试这个:

(define (function-sort functions value)
  (sort functions < #:key (lambda (f) (f value))))

For improving performance on large lists with expensive functions, pay attention to Will Ness' suggestion: using #:cache-keys? #t 为了提高具有昂贵功能的大型列表的性能,请注意Will Ness的建议:使用#:cache-keys? #t #:cache-keys? #t will prevent multiple evaluations for the same argument, and in fact will be similar to what you intended to do with map in the first place (that is: precomputing the values before sorting). #:cache-keys? #t将阻止对同一个参数进行多次评估,事实上它将类似于您打算首先使用map进行的操作(即: 排序之前预先计算值)。 Consider: 考虑:

(define (function-sort functions value)
  (sort functions < #:cache-keys? #t #:key (lambda (f) (f value))))

Either way, it works as expected: 无论哪种方式,它都按预期工作:

(define myfunctions (list (lambda (x) (+ x 3)) 
                          (lambda (x) (- 100 x))
                          (lambda (x) (* x 2))))

(define fs (function-sort myfunctions 5))

((first fs) 6)
=> 9
((second fs) 6)
=> 12
((third fs) 6)
=> 94

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM