Lambdas and Captured State
Lesson 39 of 48 in Coddy's Ruby for Java Developers course.
Java lambdas can capture only final or effectively-final local bindings. A captured mutable holder can still change, as shown here. Ruby closures can observe reassignment of a captured local binding directly. Java lambdas implement functional interfaces, while Ruby lambdas are Proc objects with their own arity and return rules.
Java: complete program
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] prefix = {"old"};
java.util.function.Function<String,String> label = text -> prefix[0] + ":" + text;
prefix[0] = "new";
System.out.println(label.apply("x"));
}
}Ruby: complete program
prefix = "old"
label = ->(text) { prefix + ":" + text }
prefix = "new"
puts label.call("x")Challenge
EasyDefine make_counter(start) returning a lambda accepting delta, adding it to captured state and returning the new state. Each call to make_counter creates independent state. solve reads start then deltas; output results space-separated, or none if no deltas.
Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.
Your code goes in exercise.rb, counter_factory.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'exercise'
require_relative 'counter_factory'
def check(value)
raise 'Public API check failed' unless value
end
a = make_counter(4); b = make_counter(9)
check(a.call(3) == 7 && b.call(-2) == 7 && a.call(1) == 8)
check(a.lambda?)
puts solve(STDIN.read)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Ruby for Java Developers
1Start with Ruby
Run Ruby FilesOutput and CommentsNames and ObjectsInteger ArithmeticTruth and Boolean LogicString OperationsSymbols and KeysRecap: Packing Slip4Mutation and Errors
Mutation and AliasesNil and Optional ValuesExceptions and ValidationEnsure and CleanupRecap: Safe Ratio7Objects in Practice
Ordering with ComparableCopies and Frozen ValuesLambdas and Captured StateCustom EnumerableRecap: Callable FilterRecap: Limited Store2Flow and Methods
Conditional ValuesCase and RangesLoops and Early ExitMethods and ReturnsDefaults and KeywordsRecap: Sensor Run5Objects and State
Modules as NamespacesClasses and InstancesReaders and WritersValidated ConstructionRecap: Wallet8Lending Desk Project
Lending Desk: CatalogLending Desk: BorrowPractice on your own: Online Ruby compiler