Menu
CoddyTech

Function Collaboration

Lesson 38 of 48 in Coddy's R for Java Developers course.

Java consumers can accept interface implementations, including functional interfaces for lambdas. R functions are first-class values retained by closures and lists. force evaluates a factory argument when its capture timing matters. Call the supplied collaborator instead of silently substituting a default implementation.

Java

import java.util.*;
import java.util.function.*;
import java.util.regex.*;
public class Main {
interface Policy {int apply(int n);}
static class DoublePolicy implements Policy {public int apply(int n){return n*2;}}
static class Order {final Policy policy; Order(Policy p){policy=p;} int total(){return policy.apply(3);}}
public static void main(String[] args) throws Exception {
Order order=new Order(new DoublePolicy()); System.out.println(order.total());
}
}

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 icon

Challenge

Easy

Implement 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="")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in R for Java Developers

Practice on your own: Online R compiler