functions(): the silent heroes of programming

academics computer science functions

Are you ever nostalgic of the days of long division? Or annoyed that a tape measure makes determining the dimensions of a new couch so simple?

If you’re like me, the answer is no. Sure, I might be able to convince myself that doing a few division problems by hand would be fun or that I might enjoy measuring my new couch in terms of bowtie pasta, rather than inches. But I couldn’t imagine doing every division problem by hand or always bringing a bag of pasta with me when I need to measure something. Just like calculators and rulers are tools that make our lives easier, functions make programming easier. 

But what is a function, anyway? Functions are pieces of code that you can use over and over again. For example, say that you want to calculate how long your readings for the week will take you. You know that you have 30 pages of readings for history, 10 pages of reading for psychology, and 22 pages for biology. You also know that you are faster at finishing your readings for history (90 seconds/page) and psychology (100 seconds/page) than for biology (120 seconds/page), so you can calculate your total reading time with the following equation:

Screen Shot 2023-08-10 at 11.36.09 AM

If you only had to do this calculation once, then writing this formula by hand makes sense. But imagine you want to calculate your reading time every week and the number of pages you are assigned is constantly changing! To save time, you could write a function. Just like an online cookie recipe changes the number of teaspoons of vanilla from 1 to 1.5 when you increase the servings from 12 to 18, your function would update the total reading time based on the number of pages you were assigned for the week. How?

Rather than using specific numbers, like 30 pages of history readings, functions rely on global variables. Global variables are essentially placeholder text that can take on different values. In our example, we might have a global variable for the number of history pages, the number of psychology pages, and the number of biology pages because these values change every week! We can re-write our formula using global variables like this:

Screen Shot 2023-08-10 at 11.38.16 AM

With this new formula, all we have to do is assign a value to each global variable (e.g., # history pages = 25, # psychology pages = 45, and # biology pages = 7), and voilà! We have a new weekly reading time.

Now that we have the intuition, how do we translate our formula into a function? First, we need to put our formula inside code that can tell our computer that we are writing a function. In R, our function (named weeklyTime, but you can name your function anything!) would look like this:

Screen Shot 2023-08-10 at 11.38.52 AM

The block of code might look scary but let us focus on three things. First, we have stored (i.e., saved for later use) our function by naming it “weeklyTime” and assigning it the values on the right of the carrot. Second, our global variables appear in two places, in the formula (just like we did above) and, newly, on the first line. The global variables on the first line are the function’s arguments or the values that a user can change every time they use the function (e.g., 30 versus 25 pages of history readings). The arguments have the same name as the global variables in our formula because if you tell your computer that you have 25 pages of history readings, then it should use 25 within the formula. Third, you only have to write this block of code once. After it is written, you can calculate your reading time by calling the function and specifying the value for each global variable. 

To illustrate, if you had 25 pages of history readings, 45 pages of psychology readings, and 7 pages of biology readings, you would write the following line of code: weeklyTime(25, 45, 7). This time, the code is much shorter because your computer already remembers the formula; all you must specify is the number of pages for each subject (other example inputs and outputs are below). Do you see how much shorter this code is than writing out the full formula – e.g., (25*90) + (45*100) + (7*120) – every time? And imagine how much more arduous the process would be with a more complicated computation.

Screen Shot 2023-08-10 at 11.39.32 AM

In summary, functions are shortcuts that allow us to use the same block of code over and over, but with different values. In the example above, we created our own function. But the beauty of programming languages is that you don’t have to do everything yourself! Many functions are pre-programmed for you, and you can use them by calling the function and specifying the value for each argument – just like we did for our handmade function. 

So, the next time you are writing code, ask yourself: Will I have to do this again? Do many people do this computation? If the answer is yes to either question, then a function might be your friend.

Comments

topicTopics
academics study skills MCAT medical school admissions SAT college admissions expository writing English MD/PhD admissions strategy writing LSAT GMAT physics GRE chemistry biology math graduate admissions academic advice ACT interview prep law school admissions test anxiety language learning career advice premed MBA admissions personal statements homework help AP exams creative writing MD study schedules test prep computer science Common Application summer activities history mathematics philosophy organic chemistry secondary applications economics supplements research 1L PSAT admissions coaching grammar law psychology statistics & probability legal studies ESL dental admissions CARS SSAT covid-19 logic games reading comprehension engineering USMLE calculus mentorship PhD admissions Spanish parents Latin biochemistry case coaching verbal reasoning DAT English literature STEM excel medical school political science skills AMCAS French Linguistics MBA coursework Tutoring Approaches academic integrity astrophysics chinese genetics letters of recommendation mechanical engineering Anki DO Social Advocacy admissions advice algebra art history artificial intelligence business careers cell biology classics dental school diversity statement gap year geometry kinematics linear algebra mental health presentations quantitative reasoning study abroad tech industry technical interviews time management work and activities 2L DMD IB exams ISEE MD/PhD programs Sentence Correction adjusting to college algorithms amino acids analysis essay athletics business skills cold emails data science finance first generation student functions graphing information sessions international students internships logic networking poetry resume revising science social sciences software engineering trigonometry units writer's block 3L AAMC Academic Interest EMT FlexMed Fourier Series Greek Health Professional Shortage Area Italian Lagrange multipliers London MD vs PhD MMI Montessori National Health Service Corps Pythagorean Theorem Python Shakespeare Step 2 TMDSAS Taylor Series Truss Analysis Zoom acids and bases active learning architecture argumentative writing art art and design schools art portfolios bacteriology bibliographies biomedicine brain teaser campus visits cantonese capacitors capital markets central limit theorem centrifugal force chemical engineering chess chromatography class participation climate change clinical experience community service constitutional law consulting cover letters curriculum dementia demonstrated interest dimensional analysis distance learning econometrics electric engineering electricity and magnetism escape velocity evolution executive function fellowships freewriting genomics harmonics health policy history of medicine history of science hybrid vehicles hydrophobic effect ideal gas law immunology induction infinite institutional actions integrated reasoning intermolecular forces intern investing investment banking lab reports linear maps mandarin chinese matrices mba medical physics meiosis microeconomics mitosis mnemonics music music theory nervous system neurology neuroscience object-oriented programming