簡體   English   中英

Scheme:更改列表中元素的值

[英]Scheme: change value of an element in a list

我討厭使用SO作為查找簡單函數的方法,但我真的找不到這樣的函數:

給出一個列表(1 2 3 4 5),我想要相當於(PHP的,Perl的,Python的)

$a = array(1, 2, 3, 4, 5);   
$a[3] = 100;  

結果如何(1 2 3 100 5)

謝謝!

你可以寫list-set! Guile,像這樣:

(define a (list 1 2 3 4))     ; a is '(1 2 3 4)

(define (list-set! list k val)
    (if (zero? k)
        (set-car! list val)
        (list-set! (cdr list) (- k 1) val)))

(list-set! a 2 100)           ; a is '(1 2 100 4)

(在DrRacket中試過這個。)

Guile有一個名為list-set!的內置函數list-set! 這完全符合您的要求,使用從零開始的索引。 對於您的示例,您將擁有:

(define a '(1 2 3 4 5))
(list-set! a 3 100)

我不認為這是標准方案,但我不知道它是否真的有效。 對於固定長度的數組,您應該使用向量:

(define a2 #(1 2 3 4 5))
(vector-set! a2 3 100)

我很確定這是語言標准的一部分。

使用沒有任何SRFI的標准功能:

(set-car! (list-tail lst k) val)

我可能有點晚了,但我有一個不同的答案。

功能程序范例的一部分似乎是盡可能避免修改數據。 出於效率原因,您可能希望在此處使用其他答案。 但除此之外,請考慮一個非變異函數,例如:

(define (list-with lst idx val)
  (if (null? lst)
    lst
    (cons
      (if (zero? idx)
        val
        (car lst))
      (list-with (cdr lst) (- idx 1) val))))

通過以下測試:

(describe "a function that returns a list with a 'changed' value"
  (it "can modify the edges of lists without having 1-off errors"
    (expect (list-with '(1 2 3 4 5) 0 99) (be equal? '(99 2 3 4 5)))
    (expect (list-with '(1 2 3 4 5) 4 99) (be equal? '(1 2 3 4 99))))
  (it "has something to do with creating new lists"
    (expect (list-with '(1 2 3 4 5) 2 99) (be equal? '(1 2 99 4 5))))
  (it "doesnt just modify the contents of the original list"
    (let ((a '(1 2 3 4 5)))
      (list-with a 2 99)
      (expect a (be equal? '(1 2 3 4 5))))))

(代碼用Chicken Scheme編寫,測試用“missbehave”庫。但它似乎是非常便攜的Scheme。)

暫無
暫無

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

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