1

如何更改 Scheme 中列表的元素。我想要一个将列表的最小元素更改为另一个数字的过程,所以

如果我有一个名为 proc 的过程并给它两个参数(一个列表和一个数字),我的过程将像这样工作: (proc (list 1 2 3 1) 9)返回'(9 2 3 9)。所以 9 代替了列表的最小值。我知道我可以应用 min 来获得最小值,但我不知道如何修改列表的单个元素。

由于Scheme没有变量来保存值,我考虑过使用let或letrec,但我不知道使用let和letrec有什么区别。

4

2 回答 2

1

This can be split into two distinct tasks - getting the lowest value in the list, then replacing that value with our new value. We can get the lowest value by running the sort function on our list and sorting by least to greatest, then using apply min to get the first element of the list.

After we've got that, we can use map to go through the list, replacing any instances of the lowest number with our new number. All in all, the complete function should look like this:

    (define (replace-least lst new)
      (let ((lowest (apply min lst)))
        (map (lambda (x) (if (= x lowest) new x)) lst)))

I tested this with DrRacket 5.3 and it performed perfectly as per the specifications provided in your question. If you have any trouble, let me know.

于 2012-11-14T05:32:58.743 回答
0

This is an improved, working solution using min:

(define (replace-min lst elt)
  (let ((m (apply min lst)))
    (map (lambda (x) (if (= x m) elt x))
         lst)))

Notice that min is the simplest way to find the minimum element in a list.

于 2012-11-14T11:24:39.227 回答