函数协作
Coddy 面向 C# 开发者的 R 语言 课程的第 38 课,共 48 课。
C# 消费者可以接受委托或接口实现作为协作者。R 函数是一等值,闭包和列表可以保留它们。当捕获时机很重要时,force 可以立即求值工厂参数。调用提供的协作者,而不是悄悄替换成默认实现。
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
var order=new Order(new DoublePolicy()); Console.WriteLine(order.Total());
interface IPolicy {int Apply(int n);}
class DoublePolicy:IPolicy {public int Apply(int n)=>n*2;}
class Order {private IPolicy policy; public Order(IPolicy p){policy=p;} public int Total()=>policy.Apply(3);}
R
new_page <- function(title){force(title);function()paste0("<",title(),">")}
page<-new_page(function()"hello")
cat(page(),"\n",sep="")当工厂参数的求值时机属于捕获约定的一部分时,请强制对其求值。
挑战
简单实现 new_formatter(prefix,transform),返回一个先调用 transform(text),再在结果前添加 prefix 的函数。输入是一个前缀和一个小写单词;适配器会注入 toupper。独立探测会注入不同的函数,你的实现必须正确使用它们。
保留已声明的公共 API。可见的锁定驱动程序会直接检查它,并打印 solve(lines)。输入符合所述约定;所有算术运算的数值都很小且有限。
你的代码应写在 Formatter.R 和 Exercise.R 中。main.R 会按顺序加载依赖项,并包含提供的输入/输出代码;不能编辑它。
亲手试试
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="")
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 R 语言中的所有课
自己练习: R 在线编译器