library(learnr) tutorial_options(exercise.reveal_solution = FALSE) gradethis::gradethis_setup() knitr::opts_chunk$set( collapse = TRUE, comment = ">", error = TRUE ) set.seed(123) muladdpow <- function(value, m, a, p) { ma <- value * m + a ma ^ p } muladd <- function(value, m, a) { muladdpow(value, m, a, 1) } mul <- function(value, m) { muladd(value, m, 0) }
If you have a complex piece of code that does a single discrete thing, then you may want to wrap it up into a function so that you can refer to it by a simple name and keep the script that calls it clear and easy to read. However, you may also want to do simpler versions of that more complex task. You can either write a completely separate function to carry out that task -- but that would be breaking our guidance about copying code back and forth -- or you can write a short and simple function that doesn't do the hard (and duplicated) work itself, but instead just calls your more complex function, perhaps with simplified arguments.
Note, you will also see all of this code on GitHub at https://github.com/SBOHVM/practicalA5 if you want to look at it there instead, or you can install it locally on your computer using
devtools::install_github("SBOHVM/practicalA5")
and play with the functions. Or you can download it by cloning the git repo athttps://github.com/SBOHVM/practicalA5.git
.
Imagine we'd written a really cool function that solves a complex task... well, here just one that multiple two numbers together, adds a third and then raises the result to a power:
muladdpow <- function(value, m, a, p) { ma <- value * m + a ma ^ p } muladdpow(1, 2, 3, 2)
Try running the code block. Play with the arguments and rerun it to see how it
works. Now try to write a function that uses this function, but only does the
multiply and add part, so you just get value * m + a
back at the end:
muladd <- function(value, m, a) { muladdpow(value, m, a, ____) } muladd(2, 3, 4) == 10
muladd <- function(value, m, a) { muladdpow(value, m, a, 1) } muladd(2, 3, 4) == 10
grade_this_code()
Then write a function mul()
that uses muladd()
but just multiplies two
numbers together, ignoring the addition:
mul <- function(value, m) { muladd(____) } mul(2, 3) == 6
mul <- function(value, m) { muladd(value, m, 0) } mul(2, 3) == 6
grade_this_code()
Finally, write a function tripler() that uses
mul()` but always multiples by
three:
tripler <- function(value) { ____ } tripler(2) == 6
tripler <- function(value) { mul(value, 3) } tripler(2) == 6
grade_this_code()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.