The expression (string-append (number->string 4) myString) evaluates to "4" , so your code prints 4 . Similarly, (string-append (number->string 5) myString) evaluates to "5" and so on. None of them actually change the value of the myString variable.
To really change the value of a variable, you need to assign this variable using the Scheme language form to assign, set! . ( ! in the name, this is a schema convention saying that this is a destructive operation, that is, one that destroys the previous value in myString and replaces it with a new one). For example, you could write:
(define myString "") (set! myString (string-append myString (number->string 4))) ;; assigns "4" to myString (set! myString (string-append myString (number->string 5))) ;; assigns "45" to myString (set! myString (string-append myString (number->string 6))) ;; assigns "456" to myString (set! myString (string-append myString (number->string 7))) ;; assigns "4567" to myString (display myString) ;; prints 4567
But instead, you can simply create the desired expression, instead of performing all these destructive operations:
(define myString (string-append (number->string 4) (string-append (number->string 5) (string-append (number->string 6) (string-append (number->string 7) ""))))) (display myString) ;; prints 4567
And at this point, instead of writing code that repeats, I would do fold-right :
(define myString (fold-right (lambda (num str) (string-append (number->string num) str)) "" (list 4 5 6 7))) (display myString) ;; prints 4567
If you need to assign "4567" global variable called myString , you can simply replace define with set! in any of the two code snippets below. However, although from time to time set! may come in handy, an idiomatic scheme tends to use set! and other destructive operations sparingly. I like to consider the exclamation mark as "Proceed with caution!"
source share