Below is an example of an awesomely simple and clear comparison of FP vs OOP.

You run a
company and you just decided to give all your employees a $10,000.00
raise. How would you tackle this situation programmatically?
In OOP:
- Create Employee class which initializes with name and salary, has a change salary instance method
- Create instances of employees
- Use the each method to change salary attribute of employees by +10,000
In FP:
- Create employees array, which is an array of arrays with name and corresponding salary
- Create a change_salary function which returns a copy of a single employee with the salary field updated
- Create a change_salaries function which maps through the employee array and delegates the calculation of the new salary to change_salary
- Use both methods to create a new dataset, named ‘happier employees’
Functional programming
1. All of your functions must accept at least one argument.
2. All of your functions must return data or another function.
3. No loops!
Functional Programming also means that when you have "code that only does something, not return a value," then you're writing something that isn't purely functional.
If (x > 3) n = 3; else n = x;
Instead of doing that, you use the return statement from the if command:
let n = (if x > 3 then 3 else x)
This hypothetical if is suddenly functional because it has no side effects; it only returns a value.
Some further reading:
http://www.ibm.com/developerworks/library/l-prog/
No comments:
Post a Comment