I am new to racket and have run into an instance where I need a mutable numeric variable
Below is a function that works thru a string of bits (101011....) and if it encounters a 1 alters a numeric variable named "value" and if it encounters a 0 has to alter that same variable "value". So when we get to the end of a string we should end up with a total for "value".
(define (implode bstr value)
(for ([c (string-length bstr)])
(display (string-ref bstr c))
(if (eqv? (string-ref bstr c) #\1) (displayln (+ (/ value 3) 17))
(displayln (/ value 3)))))
How without a mtauble variable do I have this variable change as the prgram is running please ?
Racket supports mutation. For example:
#lang racket
;; count-whales: (listof string) -> number
;; Returns a count of the number of whales in lst.
(define (count-whales lst)
(define c 0)
(for ([thing lst])
(when (equal? thing "shamu")
(set! c (add1 c))))
c)
;; Example:
(count-whales '("shamu" "donald duck" "shamu"))
You're probably used to seeing loops this way, where mutation allows us to record some running value. There's no obstacle to writing with mutation. But that being said, the above function is not idiomatic Racket. A Racketeer will instead use a loop that can accumulate a value, rather than use mutation.
Here's what the above function looks like when written with an accumulator:
#lang racket
;; count-whales: (listof string) -> number
;; Returns a count of the number of whales in lst.
(define (count-whales lst)
(for/fold ([c 0])
([thing lst])
(if (equal? thing "shamu")
(add1 c)
c)))
;; Example:
(count-whales '("shamu" "donald duck" "shamu"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With