Part 5. Functions
Functions allow us to have different output each time, functions make up the bulk of programming, and they are also reusable.
Here is how we can use functions to help us design programs
In this code here, we have a traffic light image using the above primitive.
There is something wrong in this code, we are reusing the circle primitive and we are only changing the color, In programming, repeating the same lines of code makes the code bigger and more complicated to read. Programmers generally refactor and simplify code using functions, which allows code to be reusable.
A function definition is the same as mathematical functions, which takes an input, processes it and outputs the information. Examples of math functions that you have learned in high school algebra.
Given f(x) = 2 * x;
f(2) = 2 * 2 = 4
f(6) = 2 * 6 = 12
The output varies on what we input, and this is also the concept that is applied to programming, although very abstract.
Here is how to declare a function definition in racket.
We define a function using a define primitive, on the first operand is an expression containing a name and a parameter to pass when we call the function, and the next expression is the function body. We place in the body with the parameter which we will want to change as the function value is called.
on this case, when we called the bulb function, the function that we made just earlier with the string which we will replace the parameter with, will produce the same result with few lines of code.
Let us use the function that we made for the result earlier
Same result with fewer lines of code. Yeah! Now we can design more efficient code. Rule of thumb, Don't repeat yourself, look for patterns and make it into a function.
Mga Komento
Mag-post ng isang Komento