A very basic intro to FP that concentrates on two parts: immutability and statelessness, and higher-order functions. Given at ThoughtWorks LevelUp EXP 2 (levelup.thoughtworks.com/sydney/levelup-exp-dec-2013)
// do something side-effecting in here. } ! while (someCondition) { // do something side-effecting in here. } ! foreach(var something in somethings) { // do something side-effecting in here. } State modifying by nature ! Explicitly describing control flow ! ! ! ! !
i = 0; i < coll.length; i++) { var result = f(numbers[i]); destination.push(result); } return destination; } ! ! ! ! var numbers = [1, 2, 3, 4, 5]; ! var result = map(numbers, function(n) { return n * 2; }); Utility map function handles iteration and appending ! ! ! ! ! ! Actual business logic
addTen(n) return n + 10 end ! ! result = numbers.map(addTen) ! # result => [11, 12, 13, 14, 15] Some numbers ! ! A transformer function ! ! ! Apply the transformer to each element in the list map
isEven?(n) return n % 2 == 0 end ! ! result = numbers.filter(isEven?) ! # result => [2, 4] Some numbers ! ! A filter predicate function ! ! Apply the filter to each element in the list, and keep it if is passes the predicate filter
sum(acc, number) return acc + number end ! ! result = numbers.reduce(sum, 0) ! # result => 15 Some numbers ! ! An accumulator function ! ! Apply the accumulator to each number, and the accumulated value. reduce/fold
while num_elements < 10 if n^2 % 5 == 0 sum_of_first_10 += n num_elements += 1 end n += 1 end ! puts sum_of_first_10 #=> 275 Lots of state going on. ! ! ! Not obvious what we are doing without following code through.