0

Why is list-set not working in following function in Racket:

(define (trimlist sl)
  (let ((num 0) (ss "") )
    (set! num (length sl))
    (for ((i num))
         (println i)
         (set! ss (list-ref sl i))
         (println ss)
         (set! ss (string-trim ss))
         (println ss)
         (list-set sl i ss )  )
     sl ))

>  (trimlist (list " a" "b " " c "))
0
" a"
"a"
1
"b "
"b"
2
" c "
"c"
'(" a" "b " " c ")

The println statements show that each element is getting trimmed properly but the returned list still has untrimmed items. The trimmed elements are not replacing original elements in the list.

The documentation of list-set is here: https://docs.racket-lang.org/reference/pairs.html#%28def._%28%28lib._racket%2Flist..rkt%29._list-set%29%29

Where is the problem and how can I solve it?

rnso
  • 23,686
  • 25
  • 112
  • 234

1 Answers1

2

This is because list-set is not destructive (if it was, it's name would be "list-set!"). You can fix that with

(set! sl (list-set sl i ss))

Anyway, consider also a more schemish solution, like:

(define (trim-list sl) (map string-trim sl))
dercz
  • 962
  • 6
  • 9