2.1.1 Methods in Python7 fragments
Fragment 1 of 7
def plus(a, b):
return a + b
Fragment 2 of 7
sum = plus
Fragment 3 of 7
class Arithmetic():
# Instance method
def plus1(self, a, b):
return a + b
@staticmethod
def plus2(a, b):
return a + b
Fragment 4 of 7
obj = Arithmetic() # Creates an object
print(obj.plus1(1, 2)) # Prints 3
Fragment 5 of 7
sum1 = obj.plus1
print(sum1(3, 4)) # Prints 7
Fragment 6 of 7
print(Arithmetic.plus2(5, 6)) # Prints 11
Fragment 7 of 7
sum2 = Arithmetic.plus2
print(sum2(7, 8)) # Prints 15
2.1.2 Methods in Java3 fragments
Fragment 1 of 3
public static int plus(int a, int b) {
return a + b;
}
Fragment 2 of 3
IntBinaryOperator sum = FP::plus;
System.out.println(sum.applyAsInt(3, 4));
Fragment 3 of 3
IntBinaryOperator sum2 = sum;
System.out.println(sum2.applyAsInt(3, 4));
2.1.3 Methods in Scala3 fragments
Fragment 1 of 3
def plus(a: Int, b: Int) = a + b
Fragment 2 of 3
def apply(fun: (Int, Int) => Int, a: Int, b: Int) =
fun(a, b)
apply(plus, 3, 4) // Prints 7
Fragment 3 of 3
val add = plus _ // note underscore
println(plus(1, 2)) // prints 3
println(add(3, 4)) // prints 7
2.2.1 Function Literals in Python4 fragments
Fragment 1 of 4
lambda a, b: a + b
Fragment 2 of 4
plus = lambda a, b: a + b
print(plus(3, 4)) # prints 7
Fragment 3 of 4
print((lambda a, b: a + b)(3, 4)) # prints 7
Fragment 4 of 4
def combine(fun, a):
result = a[0]
for i in range(1, len(a)):
result = fun(result, a[i])
return result
a = [1, 20, 300]
print(combine(lambda a, b: a + b, a)) # prints 321
print(combine(lambda a, b: a * b, a)) # prints 6000
2.2.2 Function Literals in Java2 fragments
Fragment 1 of 2
(a, b) -> a + b
Fragment 2 of 2
IntBinaryOperator add = (x, y) -> x + y;
System.out.println(add.applyAsInt(3, 4)); // prints 7
2.2.3 Function Literals in Scala3 fragments
Fragment 1 of 3
val subtract = (a: Int, b: Int) => a - b
Fragment 2 of 3
val subtract = (a: Int, b: Int): Int => a - b
Fragment 3 of 3
def doIt(fn: (Int, Int) => Int,
x: Int, y: Int) = fn(x, y)
2.3.1 Sorting in Python7 fragments
Fragment 1 of 7
def fun_sort(a, precedes):
i = 1
while i < len(a):
n = a[i]
j = i
i = i + 1
while j > 0 and precedes(n, a[j - 1]):
a[j] = a[j - 1]
j = j - 1
a[j] = n
Fragment 2 of 7
def smaller(a, b):
return a < b
fun_sort(numbers, smaller)
Fragment 3 of 7
fun_sort(numbers, lambda a, b: a < b)
Fragment 4 of 7
fun_sort(numbers, lambda a, b: a > b)
Fragment 5 of 7
fun_sort(numbers,
lambda a, b: a % 2 != 0 and b % 2 == 0)
Fragment 6 of 7
fun_sort(numbers, lambda a, b: a % 10 < b % 10)
Fragment 7 of 7
fun_sort(numbers,
lambda a, b: n_factors(a) < n_factors(b))
2.3.2 Sorting in Java6 fragments
Fragment 1 of 6
sort(T[] a, Comparator<? super T> c)
Fragment 2 of 6
public class PlanetLocationComparator<T>
implements java.util.Comparator<T> {
@Override
public int compare(T o1, T o2) {
Planet p1 = (Planet)o1;
Planet p2 = (Planet)o2;
return p1.location - p2.location;
}
}
Fragment 3 of 6
PlanetLocationComparator<Planet> locationSorter =
new PlanetLocationComparator<Planet>();
Arrays.sort(planets, locationSorter);
Fragment 4 of 6
Arrays.sort(planets,
(p1, p2) -> p1.location - p2.location);
Fragment 5 of 6
Arrays.sort(planets, (p1, p2) ->
(int)java.lang.Math.signum(p1.mass - p2.mass));
Fragment 6 of 6
Arrays.sort(planets, (p1, p2) ->
p1.name.compareTo(p2.name));
2.3.3 Sorting in Scala2 fragments
Fragment 1 of 2
val numbers = List(31, 41, 59, 26, 53, 49, 16)
println(numbers.sortWith((a: Int, b: Int) => a < b))
// prints List(16, 26, 31, 41, 49, 53, 59)
println(numbers.sortWith((a: Int, b: Int) => a > b))
// prints List(59, 53, 49, 41, 31, 26, 16)
println(numbers.sortWith((a: Int, b: Int) =>
a % 10 < b % 10))
// prints List(31, 41, 53, 26, 16, 59, 49)
Fragment 2 of 2
val languages = List("Python", "Java", "Scala")
println(languages.sortWith(
(a: String, b: String) => a < b))
// prints List(Java, Python, Scala)
println(languages.sortWith(
(a: String, b: String) => a.length < b.length))
// prints List(Java, Scala, Python)
3.1 Higher Order Functions in Python9 fragments
Fragment 1 of 9
def product(lst):
result = lst[0]
for i in range(1, len(lst)):
result = result * lst[i]
return result
Fragment 2 of 9
lst = [1, 2, 3, 4, 5]
print(product(lst)) # prints 120
Fragment 3 of 9
result = result + lst[i] ** 2
Fragment 4 of 9
def sum_squares(initial, lst):
result = initial
for i in range(0, len(lst)):
result = result + lst[i] ** 2
return result
Fragment 5 of 9
result = result + max(0, lst[i])
Fragment 6 of 9
def fold(initial, fun, lst):
result = initial
for i in range(0, len(lst)):
result = fun(result, lst[i])
return result
Fragment 7 of 9
def multiply(a, b):
return a * b
def count_if_odd(a, b):
return a + b % 2
def count_if_prime(a, b):
if prime(b):
return a + 1
else:
return a
def longer(a, b):
if len(a) > len(b):
return a
else:
return b
Fragment 8 of 9
print(fold(1, multiply, lst)) # prints 120
print(fold(0, count_if_odd, lst)) # prints 3
print(fold(0, count_if_prime, lst)) # prints 3
languages = ['Python', 'Java', 'Scala']
print(fold('', longer, languages))
# prints 'Python'
Fragment 9 of 9
print(fold(1, lambda a, b: a * b, lst))
print(fold(0, lambda a, b: a + b % 2, lst))
3.2 Higher Order Functions in Java6 fragments
Fragment 1 of 6
int[] ary = {1, 2, 3, 4, 5};
Fragment 2 of 6
public static int addAll(int[] ary) {
int result = ary[0];
for (int i = 1; i < ary.length; i++) {
result += ary[i];
}
return result;
}
System.out.println(addAll(ary));
Fragment 3 of 6
public static int reduce(
IntBinaryOperator fun, int[] ary) {
int result = ary[0];
for (int i = 1; i < ary.length; i++) {
result = fun.applyAsInt(result, ary[i]);
}
return result;
}
Fragment 4 of 6
public static int multiply(int a, int b) {
return a * b;
}
public static int lesser(int a, int b) {
return a < b ? a : b;
}
public static int greater(int a, int b) {
return a > b ? a : b;
}
Fragment 5 of 6
System.out.println(reduce(FP::plus, ary));
System.out.println(reduce(FP::multiply, ary));
System.out.println(reduce(FP::lesser, ary));
System.out.println(reduce(FP::greater, ary));
Fragment 6 of 6
System.out.println(
reduce((a, b) -> a + b, ary));
System.out.println(
reduce((a, b) -> a * b, ary));
System.out.println(
reduce((a, b) -> a < b ? a : b, ary));
System.out.println(
reduce((a, b) -> a > b ? a : b, ary));
3.3 Higher Order Functions in Scala5 fragments
Fragment 1 of 5
val list = List(1, 2, 3, 4, 5)
Fragment 2 of 5
def addAll(list: List[Int]): Int =
if (list.tail isEmpty) list.head
else list.head + addAll(list.tail)
println(addAll(list)) // prints 15
Fragment 3 of 5
def reduce(fun: (Int, Int) => Int,
list: List[Int]): Int =
if (list.tail isEmpty) list head
else fun(list.head, reduce(fun, list tail))
Fragment 4 of 5
def add(a: Int, b: Int) = a + b
def multiply(a: Int, b: Int) = a * b
def lesser(a: Int, b: Int) = if (a < b) a else b
def greater(a: Int, b: Int) = if (a > b) a else b
println(reduce(add, list))
println(reduce(multiply, list))
println(reduce(lesser, list))
println(reduce(greater, list))
Fragment 5 of 5
println(reduce((a: Int, b: Int) => a + b, list))
println(reduce((a: Int, b: Int) => a * b, list))
println(reduce((a: Int, b: Int) =>
if (a < b) a else b, list))
println(reduce((a: Int, b: Int) =>
if (a > b) a else b, list))
4.1 Single Abstract Methods1 fragment
Fragment 1 of 1
ActionListener listener = event -> {…}
4.2 Anonymous Inner Classes3 fragments
Fragment 1 of 3
myButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
HandleMyButtonClick();
}});
Fragment 2 of 3
myButton.addActionListener(
(ActionEvent e) -> {
HandleMyButtonClick();
});
Fragment 3 of 3
ActionListener listener = e -> {
HandleMyButtonClick();
};
myButton.addActionListener(listener);
4.3 Defining Functional Interfaces4 fragments
Fragment 1 of 4
@FunctionalInterface
public interface Diddler {
public abstract int diddle(int x);
}
Fragment 2 of 4
Diddler y = x -> 3 * x + 1;
System.out.println(y.diddle(5)); // prints 16
Fragment 3 of 4
@FunctionalInterface
public interface Fun2<A, B, R> {
public R apply(A a, B b);
}
Fragment 4 of 4
Fun2<Integer, Integer, Integer> fn =
(Integer a, Integer b) -> a % b;
System.out.println(fn.apply(20, 7)); // prints 6
4.4 Method References1 fragment
Fragment 1 of 1
import java.util.function.*;
public class MetRef {
public static void applyTo10(
IntUnaryOperator intOp) { // 1
int result = intOp.applyAsInt(10); // 2
System.out.println(result);
}
public static int square(int x) {
return x * x;
}
public int cube(int x) {
return x * x * x;
}
public static void main(final String[] args) {
// Using a lambda
applyTo10(x -> x / 2); // 3
// Using a static method
applyTo10(MetRef :: square); // 4
// Using a constructor
Supplier<MetRef> ms = MetRef :: new; // 5
MetRef m = ms.get(); // 6
System.out.println(m.getClass()); // 7
// Using an instance method
applyTo10(m :: cube); // 8
}
}
4.5 The Other Method Reference4 fragments
Fragment 1 of 4
Consumer<Integer> g = bob::setAge;
Fragment 2 of 4
g.accept(44);
Fragment 3 of 4
System.out.println("computer".indexOf("t"));
Fragment 4 of 4
String s = "computer";
Function<String, Integer> find = s::indexOf;
System.out.println(find.apply("t"));
4.6.1 IntPredicate2 fragments
Fragment 1 of 2
IntPredicate even = n -> n % 2 == 0;
System.out.println(even.test(3)); // prints false
Fragment 2 of 2
Predicate<Integer> even2 = n -> n % 2 == 0;
System.out.println(even2.test(3)); // prints false
4.6.2 Function Composition2 fragments
Fragment 1 of 2
IntPredicate big = n ->
{ System.out.print("big ");
return n > 1000; };
IntPredicate even = n ->
{ System.out.print("even ");
return n % 2 == 0; };
IntPredicate bigEven = big.and(even);
System.out.println(bigEven.test(6)); // prints: big false
System.out.println(bigEven.test(6000)); // prints: big even true
System.out.println(big.or(even).test(1001)); // prints: big true
Fragment 2 of 2
System.out.println(even.negate().test(5)); // prints: even true
IntPredicate odd = even.negate();
System.out.println(odd.test(5)); // prints: even true
5.1 If Expressions in Python1 fragment
Fragment 1 of 1
least = reduce(lambda a, b: a if a < b else b, lst)
greatest = reduce(lambda a, b: a if a > b else b, lst)
5.2 If Expressions in Java3 fragments
Fragment 1 of 3
Object ternary = true ? 123 : "abc";
Fragment 2 of 3
int ternary = true ? 123 : "abc";
Fragment 3 of 3
int score = s < 0 ? 0 : (s > 100 ? 100 : s);
5.3 If Expressions in Scala1 fragment
Fragment 1 of 1
val a = 5
val b = 8.0
val max = if (a > b) a else b
6.1 List Comprehensions in Python7 fragments
Fragment 1 of 7
[10 * x for x in nums if x < 4]
# Result is [10, 20, 30]
[1 for x in nums if even(x)]
# Result is [1, 1]
[x * x for x in nums]
# Result is [1, 4, 9, 16, 25]
[v for v in "functional" if v in "aeiou"]
# Result is ['u', 'i', 'o', 'a']
Fragment 2 of 7
print([x * x for x in
[2 * y for y in range(1, 5)]])
# Prints [4, 16, 36, 64]
Fragment 3 of 7
for n in [x // 2 if x % 2 == 0
else 3 * x + 1
for x in range(1, 5)]:
print(n)
# Prints four lines: 4, 1, 10, 2
Fragment 4 of 7
{c.upper() for c in "bookkeeper" if c in "aeiou"}
# Result is {'E', 'O'}
Fragment 5 of 7
d = {'one': 1, 'two': 2, 'three':3, 'four':4}
Fragment 6 of 7
{key:d[key] for key in d if key[0] == 't'}
# Result is {'two': 2, 'three': 3}
Fragment 7 of 7
for e in (x * x for x in [1, 2, 3]):
print(e)
# Prints 1, 4, and 9
6.3 For Expressions in Scala3 fragments
Fragment 1 of 3
for (e <- List(2, 3, 5, 7)) println(e)
// prints 2, 3, 5, 7
for (e <- 1 to 5) println(e)
// prints 1, 2, 3, 4, 5
for (e <- 1 until 5) println(e)
// prints 1, 2, 3, 4
for (e <- 1 to 10 by 3) println(e)
// prints 1, 4, 7, 10
for (e <- List.range(1, 5)) println(e)
// prints 1, 2, 3, 4
for (e <- List.range(1, 10, 3)) println(e)
// prints 1, 4, 7
for (e <- "abc") println(e)
// prints a, b, c
Fragment 2 of 3
for (i <- 2 to 10;
j <- 2 to 10)
println(i + "*" + j + "=" + i * j)
Fragment 3 of 3
for (e <- 1 to 6;
if e != 4)
println(e) // prints 1, 2, 3, 5, 6
// print the same multiplication table as before
for (i <- 2 to 10;
j <- 2 to 10;
ij = i * j)
println(i + "*" + j + "=" + ij)
for (e <- "computer";
v <- "aeiou";
if e == v)
println(e) // prints o, u, e
for (v <- "aeiou";
e <- "computer";
if e == v)
println(e) // prints e, o, u
val n = 100
for (e <- 2 to Math.sqrt(n).toInt;
if n % e == 0)
println(e) // prints 2, 4, 5, 10
// print all 2-digit numbers containing 7
for (n <- 10 to 100;
s = n.toString();
if s contains '7')
println(n)
6.4 For Comprehensions in Scala3 fragments
Fragment 1 of 3
val a = for (e <- 1 to 6;
if e != 4
) yield e
// sets a to Vector(1, 2, 3, 5, 6)
val n = 50
val b = for (e <- 2 to n;
if n % e == 0
) yield e
// sets b to Vector(2, 5, 10, 25, 50)
val c = for (e <- "computer";
if "aeiou" contains e
) yield e
// sets c to the string "oue"
Fragment 2 of 3
val p = for (
n <- 10000 to 99999;
s1 = n toString();
s2 = s1 reverse;
if s1 == s2;
d = for (x <- s1) yield x asDigit;
sum = d.sum
if sum == 20
) yield n
Fragment 3 of 3
var p: List[Int] = List()
for (n <- 10000 to 99999) {
var s1 = n toString;
var s2 = s1 reverse;
if (s1 == s2) {
var sum = 0
for (x <- s1) {
sum += x.asDigit
}
if (sum == 20) {
p = p :+ n
}
}
}
7.1 Closures in Python4 fragments
Fragment 1 of 4
x = 1
def my_closure(y):
return lambda z: x + y + z
Fragment 2 of 4
c = my_closure(10)
Fragment 3 of 4
print('c(100) is', c(100))
# prints: c(100) is 111
Fragment 4 of 4
x = 5
print('c(200) is', c(200))
# prints: c(200) is 215
7.2 Closures in Java5 fragments
Fragment 1 of 5
(x) -> x + 10
Fragment 2 of 5
IntUnaryOperator add10() {
return (x) -> x + 10;
}
Fragment 3 of 5
IntUnaryOperator adder = add10();
System.out.println(adder.applyAsInt(5)); // prints 15
Fragment 4 of 5
IntUnaryOperator addN() {
int y = 10;
return (x) -> x + y;
}
Fragment 5 of 5
IntUnaryOperator addN() {
int y = 9;
y = y + 1;
return (x) -> x + y;
}
7.3 Closures in Scala5 fragments
Fragment 1 of 5
def conversion(factor: Double) =
(x: Int) => factor * x
Fragment 2 of 5
val inch2cm = conversion(2.54)
val pounds2kg = conversion(0.453592)
print(inch2cm(12)) // Prints 30.48
print(pounds2kg(150)) // Prints 68.0388
Fragment 3 of 5
var date = new Date()
def remind(name: String) =
"\nDear " + name + ", It is now " + date +
",\nand I am writing to remind you ..."
Fragment 4 of 5
println(remind("Jane"))
Thread.sleep(1000) // pause one second
date = new Date()
println(remind("Bill"))
Fragment 5 of 5
Dear Jane, It is now Thu Nov 24 16:08:11 EST 2022,
and I am writing to remind you ...
Dear Bill, It is now Thu Nov 24 16:08:12 EST 2022,
and I am writing to remind you ...
7.4 Closure Example3 fragments
Fragment 1 of 3
def polynomial(a, b, c, d):
return lambda x: (a * x**3 + b * x**2 + c * x + d)
p = polynomial(1, 10, 100, 1000)
print(p(1), p(10)) # prints 1111 4000
Fragment 2 of 3
def poly():
return lambda x: (a * x**3 + b * x**2 + c * x + d)
f = poly()
Fragment 3 of 3
a, b, c, d = 1, 10, 100, 1000
print(f(1), f(10)) # prints 1111 4000
a = 0; d = 0
print(f(1), f(10)) # prints 110 2000
8. Currying2 fragments
Fragment 1 of 2
def formula(x, a, b, c):
return (a * x ** 2) + (b * x) + c
Fragment 2 of 2
def f(x):
def g(a):
def h(b):
def j(c):
return (a * x ** 2) + (b * x) + c
return j
return h
return g
print(f(10)(1)(2)(3)) # 1*100 + 2*10 + 3 = 123
8.1 Currying in Python6 fragments
Fragment 1 of 6
def prefix(before, text):
return before + text
Fragment 2 of 6
def note(text):
return prefix('Note: ', text)
Fragment 3 of 6
def curry2(fun, arg):
return lambda text: fun(arg, text)
note = curry2(prefix, 'Note: ')
warn = curry2(prefix, 'Warning! ')
pow2 = curry2(pow, 2)
print(note('Sealed unit.')) # prints 'Note: Sealed unit.'
print(warn('Live wire!')) # prints 'Warning! Live wire!'
print(pow2(10)) # prints 1024
Fragment 4 of 6
def curry(f, x):
return lambda *args: f(x, *args)
def formula(x, a, b, c):
return (a * x ** 2) + (b * x) + c
use_10_for_x = curry(formula, 10)
print(use_10_for_x(1, 2, 3)) # prints 123
Fragment 5 of 6
def surround(before, text, after):
return before + text + after
def enclose(fun, before, after):
return lambda text: fun(before, text, after)
parens = enclose(surround, '(', ')')
print(parens('see above')) # prints '(see above)'
Fragment 6 of 6
def enclose(before, after):
return lambda text: before + text + after
parens = enclose('(', ')')
braces = enclose('{ ', ' }')
sic = enclose('', '[sic]')
bold = enclose('<b>', '</b>')
print(parens('see above')) # prints '(see above')
print(braces('1, 2, 3')) # prints '{ 1, 2, 3 }'
print(sic('nuculear')) # prints 'nuculear[sic]'
print(bold('now!')) # prints '<b>now!</b>'
8.2 Currying in Java5 fragments
Fragment 1 of 5
public static IntUnaryOperator f1(int x) {
return new IntUnaryOperator() {
@Override
public int applyAsInt(int y) {
return x * y;
}
};
}
Fragment 2 of 5
public static Function<Integer, Integer> f2(int x) {
return y -> x * y;
}
Fragment 3 of 5
IntUnaryOperator h1 = f1(3);
System.out.println(h1.applyAsInt(7));
Fragment 4 of 5
Function h2 = f2(3);
System.out.println(h2.apply(7));
Fragment 5 of 5
IntUnaryOperator curry(int x, IntBinaryOperator op) {
return z -> op.applyAsInt(x, z);
}
IntUnaryOperator add12 = curry(12, simpleAdd);
System.out.println(add12.applyAsInt(4)); // 16
8.3 Currying in Scala3 fragments
Fragment 1 of 3
def prefix(pre: String,
text: String): String = pre + text
def curry2(f: (String, String) => String,
arg1: String) =
(arg2: String) => f(arg1, arg2)
val note = curry2(prefix, "Note: ")
val caution = curry2(prefix, "Caution: ")
println(note("Refer to the manual."))
println(caution("Unplug before opening."))
Fragment 2 of 3
def prefix(pre: String)
(text: String): String = pre + text
val warn = prefix("Warning: ") _
val danger = prefix("Danger! ")("Live wire!")
println(warn("Surface may be hot."))
println(danger)
Fragment 3 of 3
def formula(x: Int, a: Int, b: Int, c: Int) =
(a * x * x) + (b * x) + c
println(formula(10, 1, 2, 3)) // prints 123
val f10 = formula(10, _: Int, _:Int, _:Int)
println(f10(4, 5, 6)) // prints 456
val fx = formula(_: Int, 7, 8, 9)
println(fx(10)) // prints 789
9.1 Function Composition in Python4 fragments
Fragment 1 of 4
big = lambda x: x > 1000
even = lambda x: x % 2 == 0
big_even = lambda x: big(x) and even(x)
Fragment 2 of 4
def big_even(x):
return big(x) and even(x)
Fragment 3 of 4
andf = lambda f, g: lambda x: f(x) and g(x)
Fragment 4 of 4
big_even_2 = andf(big, even)
big_even_2(5) # Result is False
big_even_2(5000) # Result is True
big_even_2(9999) # Result is False
9.2 Function Composition in Java2 fragments
Fragment 1 of 2
IntUnaryOperator triple = x -> 3 * x;
IntUnaryOperator square = x -> x * x;
IntUnaryOperator tripleThenSquare =
triple.andThen(square);
IntUnaryOperator squareAfterTripling =
triple.compose(square);
System.out.println(tripleThenSquare
.applyAsInt(5));
// Prints 225
System.out.println(squareAfterTripling
.applyAsInt(5));
// Prints 75
Fragment 2 of 2
IntBinaryOperator larger =
(x, y) -> x > y ? x : y;
9.3 Function Composition in Scala3 fragments
Fragment 1 of 3
def adjust(score: Int) =
if (score < 0) 0
else if (score > 100) 100
else score
val passing = (score: Int) => score >= 70
Fragment 2 of 3
val eval = adjust _ andThen passing
Fragment 3 of 3
println(eval(69)) // Prints false
println(eval(70)) // Prints true
10.2 Optional in Java1 fragment
Fragment 1 of 1
Optional<String> a = Optional.of(s);
Optional a = Optional.of(s);
10.3 Option in Scala1 fragment
Fragment 1 of 1
gender match {
case Some(g) => println("Gender is " + g)
case None => println("Gender unknown")
}
11.1 Recursion5 fragments
Fragment 1 of 5
def last(list) =
if (list.tail.isEmpty) list.head
else last(list.tail)
Fragment 2 of 5
def sum(list) =
if (list.isEmpty) 0
else list.head + sum(list.tail)
Fragment 3 of 5
def double(list) =
if (list.isEmpty) List()
else cons(2 * list.head, double(list.tail))
Fragment 4 of 5
def append(list1, list2) = {
if (list1.isEmpty) list2
else cons(list1.head, append(list1.tail, list2))
}
Fragment 5 of 5
def reverse(list) =
rev_helper(list, List())
def rev_helper(list, acc) =
if (list.isEmpty) acc
else rev_helper(list.tail, cons(list.head, acc))
12.1 Generators in Python1 fragment
Fragment 1 of 1
def fromN(init):
n = init
while True:
yield n
n = n + 1
gen = fromN(1)
for i in range(0, 5):
print(next(gen))
12.2 Streams in Java2 fragments
Fragment 1 of 2
String[] langs = { "Python", "Java", "Scala" };
Stream s1 = Stream.of(langs);
Stream s2 = Arrays.stream(langs);
Stream s3 = Stream.of("Python", "Java", "Scala");
Stream s4 = Arrays.asList(langs).stream();
Stream s5 = new HashSet(Arrays.asList(langs)).stream();
Stream.Builder builder = Stream.builder();
builder.accept("Python");
builder.accept("Java");
builder.accept("Scala");
Stream s6 = builder.build();
Fragment 2 of 2
s5.forEach(s -> System.out.println(s));
13.1 Important Functions in Python3 fragments
Fragment 1 of 3
list(map(lambda x: 10 * x, lst))
# Result is [10, 20, 30, 40, 50, 60]
list(map(lambda x: (x, x * x), lst))
# Result is [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36)]
list(filter(lambda x: x % 2 == 0, lst))
# Result is [2, 4, 6]
reduce(lambda x, y: x * y, lst, 1)
# Result is 720
Fragment 2 of 3
def trace(fun):
def wrapper(a, b):
print("Calling", fun.__name__,
"with", a, b)
result = fun(a, b)
print(" Returning", result)
return result
return wrapper
@trace
def multiply(x, y):
return x * y
Fragment 3 of 3
Calling multiply with 5 7
Returning 35
13.2 Important Functions in Java8 fragments
Fragment 1 of 8
List<Integer> numbers = Arrays.asList(1,2,3,4,5);
Stream<Integer> nums = numbers.stream();
Fragment 2 of 8
Stream<Integer> squares = nums.map(n -> n * 2);
List<Integer> res1 =
squares.collect(Collectors.toList());
System.out.println(res1);
// Prints map: [2, 4, 6, 8, 10]
Fragment 3 of 8
public static Stream<Integer> powers(Integer x) {
List<Integer> list = new ArrayList<Integer>();
list.add(x);
list.add(x * x);
return list.stream();
}
Fragment 4 of 8
Stream<Stream<Integer>> ssi = nums.map(n -> powers(n));
Fragment 5 of 8
Stream<ArrayList<Integer>> sal =
ssi.map(x -> (ArrayList<Integer>)
x.collect(Collectors.toList()));
List<List<Integer>> csal =
sal.collect(Collectors.toList());
System.out.println("map: " + csal);
// Prints map: [[1, 1], [2, 4], [3, 9], [4, 16], [5, 25]]
Fragment 6 of 8
nums = numbers.stream();
Stream<Integer> si = nums.flatMap(n -> powers(n));
ArrayList<Integer> ali = (ArrayList<Integer>) si.collect(Collectors.toList());
System.out.println("flatMap: " + ali);
// Prints flatMap: [1, 1, 2, 4, 3, 9, 4, 16, 5, 25]
Fragment 7 of 8
Stream<Integer> evens = nums.filter(n -> n % 2 == 0);
List<Integer> res2 = evens.collect(Collectors.toList());
System.out.println("filter: " + res2);
// Prints filter: [2, 4]
Fragment 8 of 8
int sum1 = nums.reduce(0, (x, y) -> x + y);
System.out.println("reduce: " + sum1);
// Prints reduce: 15
13.3 Important Functions in Scala3 fragments
Fragment 1 of 3
for (w <- words if ! w.contains('v')) yield w.toUpperCase
words.filter(w => ! w.contains('v')).map(w => w.toUpperCase)
Fragment 2 of 3
for (w <- words; c <- w) yield c.toUpper
words.flatMap(w => w.toUpperCase)
Fragment 3 of 3
words.foldLeft("")((a, b) => if (a.length > b.length) a else b)
14.1 Pipelines in Python2 fragments
Fragment 1 of 2
basket = for_each(egg)
.purchase()
.cook()
.dye()
.dry()
.collect()
Fragment 2 of 2
basket = []
for egg in eggs:
basket.append(dry(dye(cook(purchase(egg)))))
14.2.1 Intermediate Operations2 fragments
Fragment 1 of 2
Stream.of(1, 2, 3)
.map(x -> Stream.of(x, x*x, x*x*x))
.forEach(y -> System.out.println(
Arrays.toString(y.toArray()) ));
Fragment 2 of 2
Stream.of(1, 2, 3)
.flatMap(x -> Stream.of(x, x*x, x*x*x))
.forEach(y -> System.out.println(y));
14.2.2 Terminal Operations1 fragment
Fragment 1 of 1
Stream s3 = Stream.of("Python", "Java", "Scala");
s3.forEach(s -> System.out.println(s));
14.2.4 Example2 fragments
Fragment 1 of 2
Stream.iterate(10000, n -> n + 1)
.limit(90000)
.map(n -> n.toString())
.filter(s -> s.equals(reverse(s)))
.filter(s ->
s.chars()
.map(Character::getNumericValue)
.sum() == 20)
.forEach(s -> System.out.print(s + " "));
Fragment 2 of 2
static String reverse(String s) {
return new StringBuilder(s)
.reverse()
.toString();
}
14.3 Pipelines in Scala1 fragment
Fragment 1 of 1
println(Stream.range(10000, 1000000)
.map(e => e.toString)
.filter(e => e == e.reverse)
.filter(e =>
(e.toList).map(e => e.asDigit).sum == 20)
.foreach(e => print(e + " "))
)
15.1 Examples in Python4 fragments
Fragment 1 of 4
least = my_list[0]
for i in range(1, len(my_list)):
if least < my_list[i]:
least = my_list[i]
Fragment 2 of 4
least = reduce(lambda a, b: a if a < b else b, my_list)
Fragment 3 of 4
def get_digits(number):
"""Given an int or string, return a list
of the digits in it."""
string = str(number)
return [x for x in string if x.isdigit()]
def compute_isbn_13_checksum(number):
"""Given the first 12 digits (as an
int or string) of an ISBN-13 number,
compute the 13th (checksum) digit."""
digits = get_digits(number)
sum = 0
for i in range(0, 12):
if i % 2 == 0:
sum += int(digits[i])
else:
sum += 3 * int(digits[i])
mod = sum % 10
return 0 if mod == 0 else 10 - mod
Fragment 4 of 4
def isbn13_checksum(isbn):
"""Given the first 12 digits (as an
int or string) of an ISBN-13 number,
compute the 13th (checksum) digit."""
digits = [int(x) for x in str(isbn) if x.isdigit()]
addend = lambda i:
digits[i] if i % 2 == 0
else 3 * digits[i]
mod = sum([addend(i)
for i in range(0, 12)]) % 10
return 0 if mod == 0 else 10 - mod
15.2 Examples in Java3 fragments
Fragment 1 of 3
static int least(int[] ary) {
int least = ary[0];
for (int i = 0; i < ary.length; i++) {
if (ary[i] < least) least = ary[i];
}
return least;
}
System.out.println("Least is " + least(ary));
Fragment 2 of 3
System.out.println("Least is " +
Arrays
.stream(ary)
.reduce(ary[0],
(int x, int y) ->
x < y ? x : y));
}
Fragment 3 of 3
/**
* Given a 12 digit ISBN number, compute
the 13th (checksum) digit.
*/
private static int isbn13_checksum(String s) {
// Remove possible dashes
String[] ss = s.replaceAll("-", "").split("");
String[] odds = new String[6];
String[] evens = new String[6];
for (int i = 0; i < 6; i++) {
odds[i] = ss[2 * i];
evens[i] = ss[2 * i + 1];
}
Stream<Integer> oddstream =
Stream.of(odds).map(x -> new Integer(x));
Stream<Integer> evenstream =
Stream.of(evens).map(x -> 3 * new Integer(x));
int sum = Stream.concat(oddstream, evenstream)
.reduce(0, (a, b) -> a + b);
int mod = sum % 10;
return mod == 0 ? 0 : 10 - mod;
}
15.3 Examples in Scala3 fragments
Fragment 1 of 3
def least(ls: List[Int]): Int =
if (ls.tail isEmpty) ls.head
else {
val lt = least(ls.tail)
if (ls.head < lt) ls.head else lt
}
println(least(ls))
Fragment 2 of 3
println(ls.reduceLeft((a, b) => if (a < b) a else b))
Fragment 3 of 3
def isbn13_checksum(isbn: String) = {
val total = isbn
.filter(c => c isDigit)
.map(c => c.asDigit)
.grouped(2).toList
.map(p => p(0) + 3 * p(1))
.sum
val mod = total % 10
if (mod == 0) 0 else 10 - mod
}