Function Collaboration
Lesson 38 of 48 in Coddy's R for Rust Developers course.
Rust consumers can receive generic function traits, trait objects or owned collaborators, with lifetimes governing borrowed state. R functions are first-class values retained by closures and lists. force can evaluate a factory argument when immediate capture matters. Invoke the supplied collaborator instead of replacing it with a default.
Rust
struct Policy{factor:i32}
impl Policy{fn apply(&self,n:i32)->i32{n*self.factor}}
struct Order{policy:Policy}
impl Order{fn total(&self,n:i32)->i32{self.policy.apply(n)}}
fn main() {
let order=Order{policy:Policy{factor:2}}; println!("{}",order.total(3));
}
R
new_page <- function(title){force(title);function()paste0("<",title(),">")}
page<-new_page(function()"hello")
cat(page(),"\n",sep="")Force a factory argument when its evaluation timing is part of the capture contract.
Challenge
EasyImplement new_formatter(prefix,transform) returning a function that calls transform(text) then prepends prefix. Input is a prefix and one lowercase word; the adapter injects toupper. Independent probes inject different functions, which must be respected.
Keep the declared public API. The visible locked driver checks it directly as well as printing solve(lines). Inputs satisfy the stated contract; all arithmetic is small and finite.
Your code goes in Formatter.R and Exercise.R. main.R sources dependencies in order and holds the supplied input/output code; it cannot be edited.
Try it yourself
source("Formatter.R")
source("Exercise.R")
f<-new_formatter("!",function(x)paste0(x,x));stopifnot(identical(f("ab"),"!abab"))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in R for Rust Developers
1Files and Atomic Values
Run the R FilesText and OutputAtomic VectorsDivision and ModuloNULL and Missing ValuesRecap: Parcel Charge2Logic and Iteration
Comparisons and RecyclingScalar ConditionsNamed AlternativesSafe Index SequencesBreak and NextRecap: Fare Bands5Functions and Closures
Functions and ReturnsDefaults and PromisesDots ArgumentsClosures and StateRecap: Discount Total8Collaboration and Contracts
Function CollaborationS3 Inheritance OrderS4 Validity ContractsIdentity and AttributesRecap: Grouped Counts3Collections and Ownership
Vector SubsettingHeterogeneous ListsNamed LookupValues and EnvironmentsRecap: Unique StockPractice on your own: Online R compiler