Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Racket mutable variables

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 ?

like image 618
user1907316 Avatar asked Dec 06 '22 10:12

user1907316


1 Answers

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"))
like image 115
dyoo Avatar answered Dec 24 '22 07:12

dyoo