Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the uses for parameters in Racket?

Tags:

racket

I'm trying to understand parameters in Racket for single-threaded programs and I read about it here. That said, I'm still confused about why it is useful for single-threaded programs. Why is it useful? Should I think of it as a way to implement global variables?

like image 700
JRR Avatar asked Aug 08 '20 09:08

JRR


People also ask

What is the purpose of using parameters?

Parameters allow a function to perform tasks without knowing the specific input values ahead of time. Parameters are indispensable components of functions, which programmers use to divide their code into logical blocks.

What is a parameter in Racket?

A parameter is a special kind of function that approximates the behavior of a global variable. An ordinary Racket value can be mutated with set!: 

What are parameters CPP?

Parameters. The parameter is referred to as the variables that are defined during a function declaration or definition. These variables are used to receive the arguments that are passed during a function call.


1 Answers

Racket parameters can be used to provide dynamic scoping (instead of the usual lexical scoping). It also provide thread local store.

If Racket didn't have parameters, then I am sure, more programs would use global variables.

As an example of a use case, consider a program that draws points, lines, rectangles etc. Each shape has a function that draws the shape. The user of course want to control the color used to draw the shape. One option is to let all functions have a color argument as input. It doesn't take long to realize, that most often one draws a lot of shapes using the same color - so instead of all functions taking an extra argument, we want to store the current color "outside" of the drawing functions.

We can store the current color in a global variable, but we need to consider what happens if we set the current color, call a helper function, and continues to draw. The helper function could potentially change the current color, so before calling helpers, we need to store the old value, and after we need to restore the value.

Using a parameter is easier, since the parameterize form will restore the temporarily changed bindings back to the original at the right time.

As a side-note parameters works correctly in the presence of continuations, which can be used to jump back into a some middle part of a computation.

There is an explanation of dynamic scope here:

https://en.wikipedia.org/wiki/Scope_(computer_science)#Dynamic_scoping

The final section of parameters in the Guide sums of the advantages of parameters over global variables:

https://docs.racket-lang.org/guide/parameterize.html

like image 140
soegaard Avatar answered Oct 02 '22 15:10

soegaard