Racket’s let

/ 教程, racket, english

Take a bite of racket’s Local Binding, at the first sight we might already acquire the gist about the usage of define. And then it will come to us with let.

In my view, when we are using define, mostly we are thinking over things from the middle part of process. To be specific, the fundamental define gives you the flexibility to use it whenever you need it, and no matter wherever you are at this moment. But with the thinking of using let/let*/letrec, it’s like you are thinking out of boxes and thinking before your next writting of block code. this is more like you’re imaging there exists an black box called let,and you’re going to use it to implement your next bunch of code.

The reason why I said this is because of my awareness of the flexiable and various usages of Racket’s let, and most of that has been shown as examples at Local Binding, and which usages you might notice it’s quite hard to be found out in other nowadays popular languages, at least not a more consice way.

The basic difference between let/let*/letrec is they do the binding parallelly, sequentially and recursively.

1  let loop

Notably we know let can be used for local binding, but at the same time we are binding, we can involve a loop to it. This can be useful for a one-off process. Imagine you need to handle with a list of 1 8 3 0 4 8 3 0, if you encounter a 8, then add a x following it.

> (require racket/list)
> (let loop ([lst '(1 8 3 0 4 8 3 0)]
             [result '()])
    (if (empty? lst)
        result
        (begin
          (loop (cdr lst)
                (if (= (car lst) 8)
                  (append result '(8 x))
                  (append result (list (car lst))))))))

'(1 8 x 3 0 4 8 x 3 0)

There is also another example I wrote for Qweather.

I guess using the OOP language, we have to define a method for this if we want it be compact. While Racket’s "let" has the ability to directly bind everything inside it originally.

2  let* to do processing with redefining

Let’s say we have a text love, and I need to write code to output it to %I ++love-- you | I ++love-- you%.

> (let* ([text "love"]
         [text (string-append "I ++" text "-- you")]
         [text (string-append  text "|" text)])
     (string-append "%" text "%"))

"%I ++love-- you|I ++love-- you%"

There is also another example I wrote for Yijing.

With Racket’s let*, we can redefining a variable with processes of changing its values again and again.