我想在 Racket 中实现一个并行映射功能。地方似乎是建立在正确基础上的东西,但它们对我来说是未知的领域。我认为代码应该如下所示。
#lang racket
; return xs split into n sublists
(define (chunk-into n xs)
(define N (length xs))
(cond [(= 1 n) (list xs)]
[(> n N)
(cons empty
(chunk-into (sub1 n) xs))]
[else
(define m (ceiling (/ N n)))
(cons (take xs m)
(chunk-into (sub1 n) (drop xs m)))]))
(module+ test
(check-equal? (length (chunk-into 4 (range 5))) 4)
(check-equal? (length (chunk-into 2 (range 5))) 2))
(define (parallel-map f xs)
(define n-cores (processor-count))
(define xs* (chunk-into n-cores xs))
(define ps
(for/list ([i n-cores])
(place ch
(place-channel-put
ch
(map f
(place-channel-get ch))))))
(apply append (map place-channel-put ps xs*)))
这给出了错误:
f:在以下情况下使用的标识符:f
我见过的所有示例都显示了一种设计模式,即提供一个不带参数的主函数,以某种方式习惯于实例化其他位置,但这确实很麻烦,所以我正在积极尝试避免它。这可能吗?
注意:我还尝试使用期货制作并行地图。不幸的是,对于我所有的测试,它实际上都比 map 慢(我尝试使用 fib 的递归过程版本进行测试),但如果你有任何建议可以让它更快。
(define (parallel-map f xs)
(define xs** (chunk-into (processor-count) xs))
(define fs (map (λ (xs*) (future (thunk (map f xs*)))) xs**))
(apply append (map touch fs)))