From Wikipedia:
In computer science, functional programming is a programming paradigm, a style of building the structure and elements of computer programs, that treats computation as the evaluation of mathematical functions and avoids state and mutable data.
Hrm, that probably doesn't help much. Check out some of these additional lectures / videos / stuff that helps to disambiguate the term:
- Pete Kocks, "What is functional programming?" - 3 minutes long, basic overview
- Martin Odersky, "Programming Paradigms"
Now that you have some vague idea as to what functional programming is - you want to know what it's good for... right?
- Rich Hickey, "Simple Made Easy" - thesis: imperative programs are too complex
- Martin Odersky, "Working Hard to Keep It Simple" - thesis: functional programs are better-adapted for modern hardware
- Erik Meijer, "Fundamentalist Functional Programming" - thesis: tie-dyed shirts are where it's at
- Use whatever language you like
- Once you've set the value of a variable, don't change it (even if your language allows you to)
In case #2 is a bit murky, check out these examples of legal / illegal codez:
# bad
x = [1,2,3]
x <<
# good
x = [1,2,3]
y = x + 4
# bad
x = 10
x += 1
# good
x = 10
y = x + 1
# bad
x = [1,2,3]
ys = []
append_num_plus_one = lambda { |n| ys << (n + 1) } # mutates ys (accessible via closure) as a 'side-effect'
x.each(&append_num_plus_one)
# good
x = [1,2,3]
add_one = lambda { |n| n + 1 } # a 'pure' function; accepts a value, returns a value
y = x.map(&add_one)
Functions that operate on array-like structures that return new arrays are fair-game (map, reduce). Destructive methods (Ruby's concat and map!) should be avoided at all costs!
Functions as values that can be passed around like integers / strings / whatever:
add_one = lambda { |n| n + 1 }
[1,2,3].map(&add_one)
Functions that do one or more of the following:
- Accept functions as arguments
- Return functions
// ex 1: accepts addOne function as argument
var x = [1,2,3]
x.map(function addOne(n) {
return n + 1;
}); // [2,3,4]
// ex2: returns a function, then passed to map
var addN = function(n) {
return function(m) {
return m + n;
};
};
var x = [1,2,3];
x.map(addN(5)); // [6,7,8]
- Fork this repo!
- Clone your fork:
% git clone [email protected]:username/functional-programming-weekly-challenge.git
% cd functional-programming-weekly-challenge
- Set this repo as the upstream:
% git remote add upstream [email protected]:carbonfive/functional-programming-weekly-challenge.git
- Under the folder for a given week, create a folder for your solution files. Name it after your Github username.
- Commit and push the changes to your fork.
- Create a pull request back to this repo to show off your answers!
- Pull in future challenges:
% git fetch upstream
% git merge upstream/master
Each week we will add a new folder containing a README.md presenting a challenge. For example, here is the first week's challenge!