$ whoami
Erik Wallin
Consultant at DevCode
@c01ac0ca
Paradigm = Style (characteristics, concepts, thought patterns)
Programming without side effects (???)
Don't mention the M-word!
- Vet du vad en Monad är? /erwa
- Jag vet vad en månad är. /joho
From xkcd
//List.scala
sealed abstract class List[+A] ...
override def drop(n: Int): List[A] = {
var these = this
var count = n
while (!these.isEmpty && count > 0) {
these = these.tail
count -= 1
}
these
}
...
// This is very strange for a mathematician
var x = x + 1
// Do instead
val y = x + 1
// Imperative
def gcd(x: Int, y: Int): Int = {
var a = x
var b = y
while (a != b) {
if (a > b) {
a = a − b
} else {
b = b − a
}
}
return a;
}
// Functional way with recursion
def gcd(a: Int, b: Int): Int =
if (b == 0)
a
else
gcd(b, a % b)
def id(x: Int): Int = x
def square(x: Int): Int = x * x
def powerOfTwo(x: Int): Int = if (x == 0) 1 else 2 * powerOfTwo(x - 1)
def sum(f: Int => Int, a: Int, b: Int): Int = f(a) + f(b)
//Composition
def sumInts(a: Int, b: Int): Int = sum(id, a, b)
def sumSquares(a: Int, b: Int): Int = sum(square, a, b)
def sumPowersOfTwo(a: Int, b: Int): Int = sum(powerOfTwo, a, b)
println("sum squares 2 and 4 = " + sumSquares(2, 4))
def sum(f: Int => Int, a: Int, b: Int): Int = f(a) + f(b)
println("sum quadruples 2 and 4 = " + sum(x => x * 4, 2, 4))
var factor = 3
val multiplier = i => i * factor
println("muliplier(1) value = " + multiplier(1))
println("muliplier(2) value = " + multiplier(2))
def modN(n: Int)(x: Int) = ((x % n) == 0)
def mod13 = modN(13)
println("modN(13, 8) value = " + modN(13, 8))
println("mod13(8) value = " + mod13(8))
If a java programmer should remember anything from this presentation this is it!
// Example from Oracle
// Imperative
List<Transaction> groceryTransactions = new Arraylist<>();
for (Transaction t: transactions) {
if(t.getType() == Transaction.GROCERY) {
groceryTransactions.add(t);
}
}
Collections.sort(groceryTransactions, new Comparator() {
public int compare(Transaction t1, Transaction t2) {
return t2.getValue().compareTo(t1.getValue());
}
});
List<Integer> transactionIds = new ArrayList<>();
for(Transaction t: groceryTransactions) {
transactionsIds.add(t.getId());
}
// Declarative/Functional way
List<Integer> transactionsIds =
transactions.stream()
.filter(t -> t.getType() == Transaction.GROCERY)
.sorted(Comparator.comparing(Transaction::getValue).reversed())
.map(Transaction::getId)
.collect(toList());
Single Abstract Method interfaces (SAM Interfaces) / Functional Interfaces
// Don't write a Comparator as a anonymous inner class
Collections.sort(groceryTransactions, new Comparator() {
public int compare(Transaction t1, Transaction t2) {
return t2.getValue().compareTo(t1.getValue());
}
});
// Use a lambda expression instead
Collections.sort(groceryTransactions,
(Transaction t1, Transaction t2) -> t2.getValue().compareTo(t1.getValue());
);