<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Dmcarmon</id>
	<title>Expertiza_Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Dmcarmon"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Dmcarmon"/>
	<updated>2026-05-09T20:31:59Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.41.0</generator>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=69285</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w11 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=69285"/>
		<updated>2012-10-30T02:57:27Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* More Examples */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Introduction=&lt;br /&gt;
Test driven development (TDD) is a process that tries to create the minimal amount of code while meeting customer's expectations. TDD is a component of [http://en.wikipedia.org/wiki/Extreme_programming Extreme Programming] and often used in conjunction with [http://en.wikipedia.org/wiki/Integration_test integration tests]. The premise of TDD is to test first, code second, and improve (or [http://en.wikipedia.org/wiki/Refactoring refactor]) last. This forces the software developers to focus on customer specifications first. After each iteration of testing, coding, and refactoring the programmer has a piece of ready to ship code. The rest of this chapter gives the motivation for TDD, shows the steps for TDD, outlines the principles of TDD, provides examples using TDD, and compares the pros and cons of TDD.&lt;br /&gt;
&lt;br /&gt;
=Motivation for TDD=&lt;br /&gt;
&lt;br /&gt;
There are two main motivations for TDD.&lt;br /&gt;
&lt;br /&gt;
[[File:CostofChange.png|550px|Thumb:Figure 1: Traditional &amp;quot;Cost of Change&amp;quot; curve with the waterfall model superimposed]]&lt;br /&gt;
&lt;br /&gt;
*Testing is the one activity that improves the quality of code. In various design scenarios, like waterfall model, testing occurs towards the end of the project development activity. As shown in the figure 1, introducing testing as a latter phase increases the cost incurred for implementing the changes. From this we infer that there is a high chance of reducing the costs by moving the Test phase to the initial part.&lt;br /&gt;
*The client can also be well informed about the design and can suggest changes which can be incorporated well in advance. This approach also known as TDD helps achieve flexibility to achieve the client’s ever-changing requirements&lt;br /&gt;
&lt;br /&gt;
=Principles=&lt;br /&gt;
&lt;br /&gt;
TDD follows several principles:&lt;br /&gt;
&lt;br /&gt;
*Tests serve as examples of how to use a class or method.  Once used to having tests that show how things work (and that they work), developers start inquiring if a test was already there for the piece of code to be developed&lt;br /&gt;
*Developer tests are distinctly different from QA (Quality Analysis) tests and should be kept separate.  QA tests target features and treat the system as a black box.  Unit tests created by the developer operate at a lower level and test different things.&lt;br /&gt;
*Name the tests carefully.  For Example, name test packages like the package being tested with a suffix.  For example, the &amp;quot;DataAccess&amp;quot; project/package is tested by &amp;quot;DataAccess.Test&amp;quot;. Also,  name test classes the same as the class under test with the suffix &amp;quot;Test&amp;quot;.  For example, the class &amp;quot;PrintManager&amp;quot; is tested by the test class &amp;quot;PrintManagerTest&amp;quot;.  This convention makes it easy to find the related class and keeps the class name a noun. You should also name test methods the same as the method being tested with the prefix &amp;quot;Test&amp;quot;.  For example, the method &amp;quot;PrintProductOrder()&amp;quot; is tested by the method &amp;quot;TestPrintProductOrder()&amp;quot;.  This convention keeps the method name a verb that reads as an english phrase.  &lt;br /&gt;
*Write each test before writing the method under test. It encourages the developer to think as a user of the target method before thinking about implementation, which usually results in a cleaner, easier-to-use interface.&lt;br /&gt;
*Follow the &amp;quot;3-As&amp;quot; pattern for test methods: Arrange, Act, Assert. Specifically, use separate code paragraphs (groups of lines of code separated by a blank line) for each of the As.  Arrange is variable declaration and initialization.  Act is invoking the code under test.  Assert is using the Assert.* methods to verify that expectations were met. &lt;br /&gt;
*When writing application code, only write enough code to make a test work. This technique prevents gold-plating and ensures that you always have a test for the code you write. &lt;br /&gt;
*When you find you need to refractor working code, refractor and re-test prior to writing new code.  This technique ensures your refractoring is correct prior to adding new functionality and applies to creating new methods, introducing inheritance, everything.&lt;br /&gt;
&lt;br /&gt;
=Steps=&lt;br /&gt;
[[File:TDD_Steps.png|550px|Thumb:Figure 1: Traditional &amp;quot;Cost of Change&amp;quot; curve with the waterfall model superimposed]]&lt;br /&gt;
&lt;br /&gt;
Follow these steps:&lt;br /&gt;
*Understand the requirements of the story, work item, or feature that you are working on.&lt;br /&gt;
*&amp;lt;span style=&amp;quot;color:red&amp;quot;&amp;gt;Red&amp;lt;/span&amp;gt;:Create a test and make it fail.&lt;br /&gt;
Imagine how the new code should be called and write the test as if the code already existed.&lt;br /&gt;
Create the new production code stub. Write just enough code so that it compiles.&lt;br /&gt;
Run the test. It should fail. This is a calibration measure to ensure that your test is calling the correct code and that the code is not working by accident. This is a meaningful failure, and you expect it to fail.&lt;br /&gt;
*&amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Green&amp;lt;/span&amp;gt;: Make the test pass by any means necessary.&lt;br /&gt;
Write the production code to make the test pass. Keep it simple.&lt;br /&gt;
Some advocate the hard-coding of the expected return value first to verify that the test correctly detects success. This varies from practitioner to practitioner.If you've written the code so that the test passes as intended, you are finished. You do not have to write more code speculatively. If new functionality is still needed, then another test is needed. Make this one test pass and continue.&lt;br /&gt;
When the test passes, you might want to run all tests up to this point to build confidence that everything else is still working.&lt;br /&gt;
*Refactor: Change the code to remove duplication in your project and to improve the design while ensuring that all tests still pass.&lt;br /&gt;
Remove duplication caused by the addition of the new functionality.&lt;br /&gt;
Make design changes to improve the overall solution.&lt;br /&gt;
After each refactoring, rerun all the tests to ensure that they all still pass.&lt;br /&gt;
*Repeat the cycle. Each cycle should be very short, and a typical hour should contain many Red/Green/ Refractor cycles.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
&lt;br /&gt;
==Homework Grades Program==&lt;br /&gt;
&lt;br /&gt;
===Setup===&lt;br /&gt;
As a simple example, we are creating a program that keeps track of our homework grades. We envision that we would be able to get the average of these homework grades. Step one: &amp;lt;b&amp;gt; write a test &amp;lt;/b&amp;gt;. Let's test an average function&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We will get multiple errors - this test won't even compile (but, that's ok for now). Let's take a look at what will generate error messages:&lt;br /&gt;
&lt;br /&gt;
* class &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; constructor not declared&lt;br /&gt;
* field &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* method &amp;lt;code&amp;gt;average&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
&lt;br /&gt;
Now, we fix the first error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Second error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Homework(void) {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Third error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int * grades;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fourth error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int average(int * grades) {&lt;br /&gt;
  return 0; // default return value&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, the test compiles! The code now looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
&lt;br /&gt;
    return 0; // default return value&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Red Step===&lt;br /&gt;
Now, we run the test, and the familar &amp;lt;span style=&amp;quot;color:red&amp;quot;&amp;gt;red&amp;lt;/span&amp;gt; bar of failure greets us (remember the mantra &amp;lt;span style=&amp;quot;color:red&amp;quot;&amp;gt;red&amp;lt;/span&amp;gt;-&amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;green&amp;lt;/span&amp;gt;-refactor). The assert fails. The average function needs to actually average something (not just return 0). As we think about averaging the grades, we realize we need to know how many grades are in the int array &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt;. So, we add to the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
  int numGrades;                         // new&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
 &lt;br /&gt;
   int avg = 0;                         // new&lt;br /&gt;
 &lt;br /&gt;
   for(int i = 0; i &amp;lt; numGrades; i++) { // new&lt;br /&gt;
     avg += grades[i];                  // new&lt;br /&gt;
   }                                    // new&lt;br /&gt;
 &lt;br /&gt;
   return avg/numGrades;                // new&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Of course, we must remember to change the test to:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  myHomework.numGrades = 2;&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green Step===&lt;br /&gt;
Success! We have a &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;green&amp;lt;/span&amp;gt; bar when we run it. &lt;br /&gt;
&lt;br /&gt;
===Refactoring Step===&lt;br /&gt;
The last step is refactoring. Perhaps we don't want a grade to be an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;? Should it be an &amp;lt;code&amp;gt;unsigned int&amp;lt;/code&amp;gt;? For this simple example, there isn't much refactoring to do, but in a larger example there may be multiple areas for improvement.&lt;br /&gt;
&lt;br /&gt;
==Refactoring Example==&lt;br /&gt;
The following example is take from &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck.&lt;br /&gt;
&lt;br /&gt;
Using the TDD process the author created an object with the following structure:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dollar {&lt;br /&gt;
 &lt;br /&gt;
  Dollar(int amount) {&lt;br /&gt;
     this.amount = amount;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  void times(int mulitplier) {&lt;br /&gt;
    amount *= multiplier;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
What's wrong with the code above? Look at the following test:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  &lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  five.times(2);&lt;br /&gt;
  assertEquals(10, five.amount);&lt;br /&gt;
  five.times(3);&lt;br /&gt;
  assertEquals(15, five.amount);&lt;br /&gt;
&lt;br /&gt;
}  &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Whenever we perform an operation on a &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; the value of the &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; changes. In the test above &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; isn't 5 after we multiply it by 2, and thus the name &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; doesn't make sense anymore. How do we change this? &lt;br /&gt;
&lt;br /&gt;
===Red Step===&lt;br /&gt;
&lt;br /&gt;
First, we change the &amp;lt;b&amp;gt;test&amp;lt;/b&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  Dollar product = five.times(2);&lt;br /&gt;
  assertEquals(10, product.amount);&lt;br /&gt;
  product = five.times(3);&lt;br /&gt;
  assertEquals(15, product.amount);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new test won't compile until we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  amount *= multiplier;&lt;br /&gt;
  return null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now the test compiles, but &amp;lt;span style=&amp;quot;color:red&amp;quot;&amp;gt;fails&amp;lt;/span&amp;gt;. Once again, we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  return new Dollar(amount * multiplier);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green Step===&lt;br /&gt;
&lt;br /&gt;
The test &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;succeeds&amp;lt;/span&amp;gt;. So we see that even when we are refactoring we change the test first, then the code. This way we know our refactoring is an improvement.&lt;br /&gt;
&lt;br /&gt;
==More Examples==&lt;br /&gt;
[http://catalog.lib.ncsu.edu/record/NCSU1601963 See] &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck for more examples.&lt;br /&gt;
&lt;br /&gt;
=Characteristics of a Good Unit Test=&lt;br /&gt;
A good unit test has the following characteristics.&lt;br /&gt;
*It is important that the test executes fast. If the tests are slow, they will not be run often.&lt;br /&gt;
*Environmental dependencies such as databases, file systems, networks, queues, and so on which will slow down the tests are either separated or simulated. Tests that exercise these will not run fast, and a failure does not give meaningful feedback about what the problem actually is.&lt;br /&gt;
*The scope of testing is very limited. If the test fails, it's obvious where to look for the problem. It's important to only test one aspect in a single test.&lt;br /&gt;
*The test should run and pass in isolation (on any machine). If the tests require special environmental setup or fail unexpectedly, then they are not good unit tests.&lt;br /&gt;
*Such a test often uses stubs and mock objects. If the code being tested typically calls out to a database or file system, these dependencies must be simulated, or mocked. These dependencies will ordinarily be abstracted away by using interfaces.&lt;br /&gt;
*The intention of testing is clearly revealed. Another developer can look at the test and understand what is expected of the production code.&lt;br /&gt;
&lt;br /&gt;
=Benefits of TDD=&lt;br /&gt;
&lt;br /&gt;
Using TDD has many benefits.&lt;br /&gt;
&lt;br /&gt;
*Automated testing: Automated system makes the testing much more easier and faster. Manual testing is slower and needs human interaction which is error-prone. Automated testing makes sure any particular test is not missing every time we test the system, whereas humans may leave a test out mistakenly during testing process.&lt;br /&gt;
*Better to test New/Modified Functionality: With manual testing whenever you add new functionality or modify existing functionality, QA personal needs to test all systems that may be affected due to the modification which may be time-consuming. This may also leave a hidden bug in the system after modification. With TDD whenever a new functionality is added or existing functionality is modified, the whole set of tests in the system is run to make sure existing tests are passed. This makes sure that existing functionality is not broken.&lt;br /&gt;
*Developer’s confidence: With TDD, developers are more safe to change the system as any inappropriate changes will make some tests to fail. With non-TDD system developers needs to take more care to change existing system as the new change may fail other functionality. But with TDD developers can do so easily as after modification if developer runs the test he/she will find immediately that the change has failed some other tests (i.e. some other part of the system).&lt;br /&gt;
*Manual testing stage is shortened: In non-TDD development, as soon as developers prepare a build, QA personal starts testing. This manual testing takes a reasonable amount of time and increases the time to deliver the product from the build time. With TDD, a major part of the system is tested during development and needs lesser QA involvement in the time between build and final delivery of the product.&lt;br /&gt;
*Alternative Documentation: Unit tests are kind of documentation to system. Each unit test tells about an individual requirement to the module or system. For example, the following test ensures that only a logged in user with proper balance can buy an item when the item exists in stock. This test reflects a user aspect scenario of the system.&lt;br /&gt;
&lt;br /&gt;
     public void CheckUserCanNotPurchaseItemWithoutBalance(){  &lt;br /&gt;
     LoginToTheSystem();       &lt;br /&gt;
     SelectAnItemToBuy();       &lt;br /&gt;
     MakeSureItemExsitsInStock();       &lt;br /&gt;
     MakeSureUserHasBalanceToBuy();      &lt;br /&gt;
     RunTheTransaction(); &lt;br /&gt;
  }			&lt;br /&gt;
*Better way to fix bugs: In TDD approach when QA finds a bug, developer first writes a test that generates the bug (that is the test will fail due to this bug). Then developer modifies code to make sure that the test is passed (i.e., the bug is fixed). This approach makes sure that next time the bug will not appear in the system as a test is written in the system to take care of the bug.&lt;br /&gt;
*Repetition of the same bug reduced: With TDD once a bug is found, it's put under test. So every time you run the whole test in the system, the tests associated with the bug are run and make sure the bugs are not generated again.&lt;br /&gt;
&lt;br /&gt;
=Shortcomings Of TDD=&lt;br /&gt;
&lt;br /&gt;
TDD has a few shortcomings:&lt;br /&gt;
&lt;br /&gt;
*The actual database or external file is never tested directly by TDD (only production code can test it)&lt;br /&gt;
*If not used carefully, it can add to the total project costs and complexity of the project&lt;br /&gt;
*TDD is unable to test UI.&lt;br /&gt;
*TDD is highly reliant on Refactoring and Programmer Skills.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
&lt;br /&gt;
TDD fundamentaly changes how a developer approaches a programming project. It forces him to focus on the design requirements first by mandating that the developer must write a test for anything before he writes code to do it. It has many benefits including ensuring that the project is well tested and, in some cases, reducing development time. However, it is limited in that it can't test user interfaces or databases directly. Overall, it is a very effective tool for quickly writing well tested code.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
*[http://catalog.lib.ncsu.edu/record/NCSU1601963 Beck, K. (2002). Test-driven development by example. Addison-Wesley.]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Test_driven_development (n.d.). Test-driven development. website: http://en.wikipedia.org/wiki/Test_driven_development]&lt;br /&gt;
*[http://c2.com/cgi/wiki?TestDrivenDevelopment (2012, January 11). Test driven development. website: http://c2.com/cgi/wiki?TestDrivenDevelopment]&lt;br /&gt;
*[http://www.agiledata.org/essays/tdd.html Ambler, S. W. (2002). Introduction to test driven development (tdd). Retrieved from Agile Data website: http://www.agiledata.org/essays/tdd.html]&lt;br /&gt;
*[http://www.methodsandtools.com/archive/archive.php?id=20 Murphy, Craig. (n. d.). Methods and Tools Archives website: http://www.methodsandtools.com/archive/archive.php?id=20]&lt;br /&gt;
*[http://www.martinfowler.com/bliki/TestDrivenDevelopment.html Fowler, Martin. (n. d.). Test Driven Development website: www.martinfowler.com/bliki/TestDrivenDevelopment]&lt;br /&gt;
*[http://www.codeproject.com/Articles/47747/Test-Driven-Development-TDD-Step-by-Step-Part-1-In Sohel, Rana. (2009 December, 17). TDD Step by Step Code Project website: http://www.codeproject.com/Articles/47747/Test-Driven-Development-TDD-Step-by-Step-Part-1-In]&lt;br /&gt;
*[http://integralpath.blogs.com/thinkingoutloud/2005/09/principles_of_t.html Girvin, T.(2005, September 9) Principles for Test-Driven Development website: http://integralpath.blogs.com/thinkingoutloud/2005/09/principles_of_t.html]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=69284</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w11 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=69284"/>
		<updated>2012-10-30T02:57:05Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Introduction=&lt;br /&gt;
Test driven development (TDD) is a process that tries to create the minimal amount of code while meeting customer's expectations. TDD is a component of [http://en.wikipedia.org/wiki/Extreme_programming Extreme Programming] and often used in conjunction with [http://en.wikipedia.org/wiki/Integration_test integration tests]. The premise of TDD is to test first, code second, and improve (or [http://en.wikipedia.org/wiki/Refactoring refactor]) last. This forces the software developers to focus on customer specifications first. After each iteration of testing, coding, and refactoring the programmer has a piece of ready to ship code. The rest of this chapter gives the motivation for TDD, shows the steps for TDD, outlines the principles of TDD, provides examples using TDD, and compares the pros and cons of TDD.&lt;br /&gt;
&lt;br /&gt;
=Motivation for TDD=&lt;br /&gt;
&lt;br /&gt;
There are two main motivations for TDD.&lt;br /&gt;
&lt;br /&gt;
[[File:CostofChange.png|550px|Thumb:Figure 1: Traditional &amp;quot;Cost of Change&amp;quot; curve with the waterfall model superimposed]]&lt;br /&gt;
&lt;br /&gt;
*Testing is the one activity that improves the quality of code. In various design scenarios, like waterfall model, testing occurs towards the end of the project development activity. As shown in the figure 1, introducing testing as a latter phase increases the cost incurred for implementing the changes. From this we infer that there is a high chance of reducing the costs by moving the Test phase to the initial part.&lt;br /&gt;
*The client can also be well informed about the design and can suggest changes which can be incorporated well in advance. This approach also known as TDD helps achieve flexibility to achieve the client’s ever-changing requirements&lt;br /&gt;
&lt;br /&gt;
=Principles=&lt;br /&gt;
&lt;br /&gt;
TDD follows several principles:&lt;br /&gt;
&lt;br /&gt;
*Tests serve as examples of how to use a class or method.  Once used to having tests that show how things work (and that they work), developers start inquiring if a test was already there for the piece of code to be developed&lt;br /&gt;
*Developer tests are distinctly different from QA (Quality Analysis) tests and should be kept separate.  QA tests target features and treat the system as a black box.  Unit tests created by the developer operate at a lower level and test different things.&lt;br /&gt;
*Name the tests carefully.  For Example, name test packages like the package being tested with a suffix.  For example, the &amp;quot;DataAccess&amp;quot; project/package is tested by &amp;quot;DataAccess.Test&amp;quot;. Also,  name test classes the same as the class under test with the suffix &amp;quot;Test&amp;quot;.  For example, the class &amp;quot;PrintManager&amp;quot; is tested by the test class &amp;quot;PrintManagerTest&amp;quot;.  This convention makes it easy to find the related class and keeps the class name a noun. You should also name test methods the same as the method being tested with the prefix &amp;quot;Test&amp;quot;.  For example, the method &amp;quot;PrintProductOrder()&amp;quot; is tested by the method &amp;quot;TestPrintProductOrder()&amp;quot;.  This convention keeps the method name a verb that reads as an english phrase.  &lt;br /&gt;
*Write each test before writing the method under test. It encourages the developer to think as a user of the target method before thinking about implementation, which usually results in a cleaner, easier-to-use interface.&lt;br /&gt;
*Follow the &amp;quot;3-As&amp;quot; pattern for test methods: Arrange, Act, Assert. Specifically, use separate code paragraphs (groups of lines of code separated by a blank line) for each of the As.  Arrange is variable declaration and initialization.  Act is invoking the code under test.  Assert is using the Assert.* methods to verify that expectations were met. &lt;br /&gt;
*When writing application code, only write enough code to make a test work. This technique prevents gold-plating and ensures that you always have a test for the code you write. &lt;br /&gt;
*When you find you need to refractor working code, refractor and re-test prior to writing new code.  This technique ensures your refractoring is correct prior to adding new functionality and applies to creating new methods, introducing inheritance, everything.&lt;br /&gt;
&lt;br /&gt;
=Steps=&lt;br /&gt;
[[File:TDD_Steps.png|550px|Thumb:Figure 1: Traditional &amp;quot;Cost of Change&amp;quot; curve with the waterfall model superimposed]]&lt;br /&gt;
&lt;br /&gt;
Follow these steps:&lt;br /&gt;
*Understand the requirements of the story, work item, or feature that you are working on.&lt;br /&gt;
*&amp;lt;span style=&amp;quot;color:red&amp;quot;&amp;gt;Red&amp;lt;/span&amp;gt;:Create a test and make it fail.&lt;br /&gt;
Imagine how the new code should be called and write the test as if the code already existed.&lt;br /&gt;
Create the new production code stub. Write just enough code so that it compiles.&lt;br /&gt;
Run the test. It should fail. This is a calibration measure to ensure that your test is calling the correct code and that the code is not working by accident. This is a meaningful failure, and you expect it to fail.&lt;br /&gt;
*&amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Green&amp;lt;/span&amp;gt;: Make the test pass by any means necessary.&lt;br /&gt;
Write the production code to make the test pass. Keep it simple.&lt;br /&gt;
Some advocate the hard-coding of the expected return value first to verify that the test correctly detects success. This varies from practitioner to practitioner.If you've written the code so that the test passes as intended, you are finished. You do not have to write more code speculatively. If new functionality is still needed, then another test is needed. Make this one test pass and continue.&lt;br /&gt;
When the test passes, you might want to run all tests up to this point to build confidence that everything else is still working.&lt;br /&gt;
*Refactor: Change the code to remove duplication in your project and to improve the design while ensuring that all tests still pass.&lt;br /&gt;
Remove duplication caused by the addition of the new functionality.&lt;br /&gt;
Make design changes to improve the overall solution.&lt;br /&gt;
After each refactoring, rerun all the tests to ensure that they all still pass.&lt;br /&gt;
*Repeat the cycle. Each cycle should be very short, and a typical hour should contain many Red/Green/ Refractor cycles.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
&lt;br /&gt;
==Homework Grades Program==&lt;br /&gt;
&lt;br /&gt;
===Setup===&lt;br /&gt;
As a simple example, we are creating a program that keeps track of our homework grades. We envision that we would be able to get the average of these homework grades. Step one: &amp;lt;b&amp;gt; write a test &amp;lt;/b&amp;gt;. Let's test an average function&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We will get multiple errors - this test won't even compile (but, that's ok for now). Let's take a look at what will generate error messages:&lt;br /&gt;
&lt;br /&gt;
* class &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; constructor not declared&lt;br /&gt;
* field &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* method &amp;lt;code&amp;gt;average&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
&lt;br /&gt;
Now, we fix the first error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Second error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Homework(void) {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Third error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int * grades;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fourth error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int average(int * grades) {&lt;br /&gt;
  return 0; // default return value&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, the test compiles! The code now looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
&lt;br /&gt;
    return 0; // default return value&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Red Step===&lt;br /&gt;
Now, we run the test, and the familar &amp;lt;span style=&amp;quot;color:red&amp;quot;&amp;gt;red&amp;lt;/span&amp;gt; bar of failure greets us (remember the mantra &amp;lt;span style=&amp;quot;color:red&amp;quot;&amp;gt;red&amp;lt;/span&amp;gt;-&amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;green&amp;lt;/span&amp;gt;-refactor). The assert fails. The average function needs to actually average something (not just return 0). As we think about averaging the grades, we realize we need to know how many grades are in the int array &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt;. So, we add to the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
  int numGrades;                         // new&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
 &lt;br /&gt;
   int avg = 0;                         // new&lt;br /&gt;
 &lt;br /&gt;
   for(int i = 0; i &amp;lt; numGrades; i++) { // new&lt;br /&gt;
     avg += grades[i];                  // new&lt;br /&gt;
   }                                    // new&lt;br /&gt;
 &lt;br /&gt;
   return avg/numGrades;                // new&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Of course, we must remember to change the test to:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  myHomework.numGrades = 2;&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green Step===&lt;br /&gt;
Success! We have a &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;green&amp;lt;/span&amp;gt; bar when we run it. &lt;br /&gt;
&lt;br /&gt;
===Refactoring Step===&lt;br /&gt;
The last step is refactoring. Perhaps we don't want a grade to be an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;? Should it be an &amp;lt;code&amp;gt;unsigned int&amp;lt;/code&amp;gt;? For this simple example, there isn't much refactoring to do, but in a larger example there may be multiple areas for improvement.&lt;br /&gt;
&lt;br /&gt;
==Refactoring Example==&lt;br /&gt;
The following example is take from &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck.&lt;br /&gt;
&lt;br /&gt;
Using the TDD process the author created an object with the following structure:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dollar {&lt;br /&gt;
 &lt;br /&gt;
  Dollar(int amount) {&lt;br /&gt;
     this.amount = amount;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  void times(int mulitplier) {&lt;br /&gt;
    amount *= multiplier;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
What's wrong with the code above? Look at the following test:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  &lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  five.times(2);&lt;br /&gt;
  assertEquals(10, five.amount);&lt;br /&gt;
  five.times(3);&lt;br /&gt;
  assertEquals(15, five.amount);&lt;br /&gt;
&lt;br /&gt;
}  &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Whenever we perform an operation on a &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; the value of the &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; changes. In the test above &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; isn't 5 after we multiply it by 2, and thus the name &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; doesn't make sense anymore. How do we change this? &lt;br /&gt;
&lt;br /&gt;
===Red Step===&lt;br /&gt;
&lt;br /&gt;
First, we change the &amp;lt;b&amp;gt;test&amp;lt;/b&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  Dollar product = five.times(2);&lt;br /&gt;
  assertEquals(10, product.amount);&lt;br /&gt;
  product = five.times(3);&lt;br /&gt;
  assertEquals(15, product.amount);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new test won't compile until we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  amount *= multiplier;&lt;br /&gt;
  return null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now the test compiles, but &amp;lt;span style=&amp;quot;color:red&amp;quot;&amp;gt;fails&amp;lt;/span&amp;gt;. Once again, we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  return new Dollar(amount * multiplier);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green Step===&lt;br /&gt;
&lt;br /&gt;
The test &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;succeeds&amp;lt;/span&amp;gt;. So we see that even when we are refactoring we change the test first, then the code. This way we know our refactoring is an improvement.&lt;br /&gt;
&lt;br /&gt;
==More Examples==&lt;br /&gt;
See &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck for more examples.&lt;br /&gt;
&lt;br /&gt;
=Characteristics of a Good Unit Test=&lt;br /&gt;
A good unit test has the following characteristics.&lt;br /&gt;
*It is important that the test executes fast. If the tests are slow, they will not be run often.&lt;br /&gt;
*Environmental dependencies such as databases, file systems, networks, queues, and so on which will slow down the tests are either separated or simulated. Tests that exercise these will not run fast, and a failure does not give meaningful feedback about what the problem actually is.&lt;br /&gt;
*The scope of testing is very limited. If the test fails, it's obvious where to look for the problem. It's important to only test one aspect in a single test.&lt;br /&gt;
*The test should run and pass in isolation (on any machine). If the tests require special environmental setup or fail unexpectedly, then they are not good unit tests.&lt;br /&gt;
*Such a test often uses stubs and mock objects. If the code being tested typically calls out to a database or file system, these dependencies must be simulated, or mocked. These dependencies will ordinarily be abstracted away by using interfaces.&lt;br /&gt;
*The intention of testing is clearly revealed. Another developer can look at the test and understand what is expected of the production code.&lt;br /&gt;
&lt;br /&gt;
=Benefits of TDD=&lt;br /&gt;
&lt;br /&gt;
Using TDD has many benefits.&lt;br /&gt;
&lt;br /&gt;
*Automated testing: Automated system makes the testing much more easier and faster. Manual testing is slower and needs human interaction which is error-prone. Automated testing makes sure any particular test is not missing every time we test the system, whereas humans may leave a test out mistakenly during testing process.&lt;br /&gt;
*Better to test New/Modified Functionality: With manual testing whenever you add new functionality or modify existing functionality, QA personal needs to test all systems that may be affected due to the modification which may be time-consuming. This may also leave a hidden bug in the system after modification. With TDD whenever a new functionality is added or existing functionality is modified, the whole set of tests in the system is run to make sure existing tests are passed. This makes sure that existing functionality is not broken.&lt;br /&gt;
*Developer’s confidence: With TDD, developers are more safe to change the system as any inappropriate changes will make some tests to fail. With non-TDD system developers needs to take more care to change existing system as the new change may fail other functionality. But with TDD developers can do so easily as after modification if developer runs the test he/she will find immediately that the change has failed some other tests (i.e. some other part of the system).&lt;br /&gt;
*Manual testing stage is shortened: In non-TDD development, as soon as developers prepare a build, QA personal starts testing. This manual testing takes a reasonable amount of time and increases the time to deliver the product from the build time. With TDD, a major part of the system is tested during development and needs lesser QA involvement in the time between build and final delivery of the product.&lt;br /&gt;
*Alternative Documentation: Unit tests are kind of documentation to system. Each unit test tells about an individual requirement to the module or system. For example, the following test ensures that only a logged in user with proper balance can buy an item when the item exists in stock. This test reflects a user aspect scenario of the system.&lt;br /&gt;
&lt;br /&gt;
     public void CheckUserCanNotPurchaseItemWithoutBalance(){  &lt;br /&gt;
     LoginToTheSystem();       &lt;br /&gt;
     SelectAnItemToBuy();       &lt;br /&gt;
     MakeSureItemExsitsInStock();       &lt;br /&gt;
     MakeSureUserHasBalanceToBuy();      &lt;br /&gt;
     RunTheTransaction(); &lt;br /&gt;
  }			&lt;br /&gt;
*Better way to fix bugs: In TDD approach when QA finds a bug, developer first writes a test that generates the bug (that is the test will fail due to this bug). Then developer modifies code to make sure that the test is passed (i.e., the bug is fixed). This approach makes sure that next time the bug will not appear in the system as a test is written in the system to take care of the bug.&lt;br /&gt;
*Repetition of the same bug reduced: With TDD once a bug is found, it's put under test. So every time you run the whole test in the system, the tests associated with the bug are run and make sure the bugs are not generated again.&lt;br /&gt;
&lt;br /&gt;
=Shortcomings Of TDD=&lt;br /&gt;
&lt;br /&gt;
TDD has a few shortcomings:&lt;br /&gt;
&lt;br /&gt;
*The actual database or external file is never tested directly by TDD (only production code can test it)&lt;br /&gt;
*If not used carefully, it can add to the total project costs and complexity of the project&lt;br /&gt;
*TDD is unable to test UI.&lt;br /&gt;
*TDD is highly reliant on Refactoring and Programmer Skills.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
&lt;br /&gt;
TDD fundamentaly changes how a developer approaches a programming project. It forces him to focus on the design requirements first by mandating that the developer must write a test for anything before he writes code to do it. It has many benefits including ensuring that the project is well tested and, in some cases, reducing development time. However, it is limited in that it can't test user interfaces or databases directly. Overall, it is a very effective tool for quickly writing well tested code.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
*[http://catalog.lib.ncsu.edu/record/NCSU1601963 Beck, K. (2002). Test-driven development by example. Addison-Wesley.]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Test_driven_development (n.d.). Test-driven development. website: http://en.wikipedia.org/wiki/Test_driven_development]&lt;br /&gt;
*[http://c2.com/cgi/wiki?TestDrivenDevelopment (2012, January 11). Test driven development. website: http://c2.com/cgi/wiki?TestDrivenDevelopment]&lt;br /&gt;
*[http://www.agiledata.org/essays/tdd.html Ambler, S. W. (2002). Introduction to test driven development (tdd). Retrieved from Agile Data website: http://www.agiledata.org/essays/tdd.html]&lt;br /&gt;
*[http://www.methodsandtools.com/archive/archive.php?id=20 Murphy, Craig. (n. d.). Methods and Tools Archives website: http://www.methodsandtools.com/archive/archive.php?id=20]&lt;br /&gt;
*[http://www.martinfowler.com/bliki/TestDrivenDevelopment.html Fowler, Martin. (n. d.). Test Driven Development website: www.martinfowler.com/bliki/TestDrivenDevelopment]&lt;br /&gt;
*[http://www.codeproject.com/Articles/47747/Test-Driven-Development-TDD-Step-by-Step-Part-1-In Sohel, Rana. (2009 December, 17). TDD Step by Step Code Project website: http://www.codeproject.com/Articles/47747/Test-Driven-Development-TDD-Step-by-Step-Part-1-In]&lt;br /&gt;
*[http://integralpath.blogs.com/thinkingoutloud/2005/09/principles_of_t.html Girvin, T.(2005, September 9) Principles for Test-Driven Development website: http://integralpath.blogs.com/thinkingoutloud/2005/09/principles_of_t.html]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=69283</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w11 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=69283"/>
		<updated>2012-10-30T02:12:19Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: Updated page based on review feedback&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Introduction=&lt;br /&gt;
Test driven development (TDD) is a process that tries to create the minimal amount of code while meeting customer's expectations. TDD is a component of [http://en.wikipedia.org/wiki/Extreme_programming Extreme Programming] and often used in conjunction with [http://en.wikipedia.org/wiki/Integration_test integration tests]. The premise of TDD is to test first, code second, and improve (or [http://en.wikipedia.org/wiki/Refactoring refactor]) last. This forces the software developers to focus on customer specifications first. After each iteration of testing, coding, and refactoring the programmer has a piece of ready to ship code. The rest of this chapter gives the motivation for TDD, shows the steps for TDD, outlines the principles of TDD, provides examples using TDD, and compares the pros and cons of TDD.&lt;br /&gt;
&lt;br /&gt;
=Motivation for TDD=&lt;br /&gt;
&lt;br /&gt;
There are two main motivations for TDD.&lt;br /&gt;
&lt;br /&gt;
[[File:CostofChange.png|550px|Thumb:Figure 1: Traditional &amp;quot;Cost of Change&amp;quot; curve with the waterfall model superimposed]]&lt;br /&gt;
&lt;br /&gt;
*Testing is the one activity that improves the quality of code. In various design scenarios, like waterfall model, testing occurs towards the end of the project development activity. As shown in the figure 1, introducing testing as a latter phase increases the cost incurred for implementing the changes. From this we infer that there is a high chance of reducing the costs by moving the Test phase to the initial part.&lt;br /&gt;
*The client can also be well informed about the design and can suggest changes which can be incorporated well in advance. This approach also known as TDD helps achieve flexibility to achieve the client’s ever-changing requirements&lt;br /&gt;
&lt;br /&gt;
=Principles=&lt;br /&gt;
&lt;br /&gt;
TDD follows several principles:&lt;br /&gt;
&lt;br /&gt;
*Tests serve as examples of how to use a class or method.  Once used to having tests that show how things work (and that they work), developers start inquiring if a test was already there for the piece of code to be developed&lt;br /&gt;
*Developer tests are distinctly different from QA (Quality Analysis) tests and should be kept separate.  QA tests target features and treat the system as a black box.  Unit tests created by the developer operate at a lower level and test different things.&lt;br /&gt;
*Name the tests carefully.  For Example, name test packages like the package being tested with a suffix.  For example, the &amp;quot;DataAccess&amp;quot; project/package is tested by &amp;quot;DataAccess.Test&amp;quot;. Also,  name test classes the same as the class under test with the suffix &amp;quot;Test&amp;quot;.  For example, the class &amp;quot;PrintManager&amp;quot; is tested by the test class &amp;quot;PrintManagerTest&amp;quot;.  This convention makes it easy to find the related class and keeps the class name a noun. You should also name test methods the same as the method being tested with the prefix &amp;quot;Test&amp;quot;.  For example, the method &amp;quot;PrintProductOrder()&amp;quot; is tested by the method &amp;quot;TestPrintProductOrder()&amp;quot;.  This convention keeps the method name a verb that reads as an english phrase.  &lt;br /&gt;
*Write each test before writing the method under test. It encourages the developer to think as a user of the target method before thinking about implementation, which usually results in a cleaner, easier-to-use interface.&lt;br /&gt;
*Follow the &amp;quot;3-As&amp;quot; pattern for test methods: Arrange, Act, Assert. Specifically, use separate code paragraphs (groups of lines of code separated by a blank line) for each of the As.  Arrange is variable declaration and initialization.  Act is invoking the code under test.  Assert is using the Assert.* methods to verify that expectations were met. &lt;br /&gt;
*When writing application code, only write enough code to make a test work. This technique prevents gold-plating and ensures that you always have a test for the code you write. &lt;br /&gt;
*When you find you need to refractor working code, refractor and re-test prior to writing new code.  This technique ensures your refractoring is correct prior to adding new functionality and applies to creating new methods, introducing inheritance, everything.&lt;br /&gt;
&lt;br /&gt;
=Steps=&lt;br /&gt;
[[File:TDD_Steps.png|550px|Thumb:Figure 1: Traditional &amp;quot;Cost of Change&amp;quot; curve with the waterfall model superimposed]]&lt;br /&gt;
&lt;br /&gt;
Follow these steps:&lt;br /&gt;
*Understand the requirements of the story, work item, or feature that you are working on.&lt;br /&gt;
*&amp;lt;span style=&amp;quot;color:red&amp;quot;&amp;gt;Red&amp;lt;/span&amp;gt;:Create a test and make it fail.&lt;br /&gt;
Imagine how the new code should be called and write the test as if the code already existed.&lt;br /&gt;
Create the new production code stub. Write just enough code so that it compiles.&lt;br /&gt;
Run the test. It should fail. This is a calibration measure to ensure that your test is calling the correct code and that the code is not working by accident. This is a meaningful failure, and you expect it to fail.&lt;br /&gt;
*&amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Green&amp;lt;/span&amp;gt;: Make the test pass by any means necessary.&lt;br /&gt;
Write the production code to make the test pass. Keep it simple.&lt;br /&gt;
Some advocate the hard-coding of the expected return value first to verify that the test correctly detects success. This varies from practitioner to practitioner.If you've written the code so that the test passes as intended, you are finished. You do not have to write more code speculatively. If new functionality is still needed, then another test is needed. Make this one test pass and continue.&lt;br /&gt;
When the test passes, you might want to run all tests up to this point to build confidence that everything else is still working.&lt;br /&gt;
*Refactor: Change the code to remove duplication in your project and to improve the design while ensuring that all tests still pass.&lt;br /&gt;
Remove duplication caused by the addition of the new functionality.&lt;br /&gt;
Make design changes to improve the overall solution.&lt;br /&gt;
After each refactoring, rerun all the tests to ensure that they all still pass.&lt;br /&gt;
*Repeat the cycle. Each cycle should be very short, and a typical hour should contain many Red/Green/ Refractor cycles.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
&lt;br /&gt;
==Homework Grades Program==&lt;br /&gt;
&lt;br /&gt;
===Setup===&lt;br /&gt;
As a simple example, we are creating a program that keeps track of our homework grades. We envision that we would be able to get the average of these homework grades. Step one: &amp;lt;b&amp;gt; write a test &amp;lt;/b&amp;gt;. Let's test an average function&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We will get multiple errors - this test won't even compile (but, that's ok for now). Let's take a look at what will generate error messages:&lt;br /&gt;
&lt;br /&gt;
* class &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; constructor not declared&lt;br /&gt;
* field &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* method &amp;lt;code&amp;gt;average&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
&lt;br /&gt;
Now, we fix the first error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Second error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Homework(void) {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Third error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int * grades;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fourth error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int average(int * grades) {&lt;br /&gt;
  return 0; // default return value&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, the test compiles! The code now looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
&lt;br /&gt;
    return 0; // default return value&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Red Step===&lt;br /&gt;
Now, we run the test, and the familar &amp;lt;span style=&amp;quot;color:red&amp;quot;&amp;gt;red&amp;lt;/span&amp;gt; bar of failure greets us (remember the mantra &amp;lt;span style=&amp;quot;color:red&amp;quot;&amp;gt;red&amp;lt;/span&amp;gt;-&amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;green&amp;lt;/span&amp;gt;-refactor). The assert fails. The average function needs to actually average something (not just return 0). As we think about averaging the grades, we realize we need to know how many grades are in the int array &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt;. So, we add to the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
  int numGrades;                         // new&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
 &lt;br /&gt;
   int avg = 0;                         // new&lt;br /&gt;
 &lt;br /&gt;
   for(int i = 0; i &amp;lt; numGrades; i++) { // new&lt;br /&gt;
     avg += grades[i];                  // new&lt;br /&gt;
   }                                    // new&lt;br /&gt;
 &lt;br /&gt;
   return avg/numGrades;                // new&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Of course, we must remember to change the test to:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  myHomework.numGrades = 2;&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green Step===&lt;br /&gt;
Success! We have a &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;green&amp;lt;/span&amp;gt; bar when we run it. &lt;br /&gt;
&lt;br /&gt;
===Refactoring Step===&lt;br /&gt;
The last step is refactoring. Perhaps we don't want a grade to be an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;? Should it be an &amp;lt;code&amp;gt;unsigned int&amp;lt;/code&amp;gt;? For this simple example, there isn't much refactoring to do, but in a larger example there may be multiple areas for improvement.&lt;br /&gt;
&lt;br /&gt;
==Refactoring Example==&lt;br /&gt;
The following example is take from &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck.&lt;br /&gt;
&lt;br /&gt;
Using the TDD process the author created an object with the following structure:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dollar {&lt;br /&gt;
 &lt;br /&gt;
  Dollar(int amount) {&lt;br /&gt;
     this.amount = amount;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  void times(int mulitplier) {&lt;br /&gt;
    amount *= multiplier;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
What's wrong with the code above? Look at the following test:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  &lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  five.times(2);&lt;br /&gt;
  assertEquals(10, five.amount);&lt;br /&gt;
  five.times(3);&lt;br /&gt;
  assertEquals(15, five.amount);&lt;br /&gt;
&lt;br /&gt;
}  &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Whenever we perform an operation on a &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; the value of the &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; changes. In the test above &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; isn't 5 after we multiply it by 2, and thus the name &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; doesn't make sense anymore. How do we change this? &lt;br /&gt;
&lt;br /&gt;
===Red Step===&lt;br /&gt;
&lt;br /&gt;
First, we change the &amp;lt;b&amp;gt;test&amp;lt;/b&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  Dollar product = five.times(2);&lt;br /&gt;
  assertEquals(10, product.amount);&lt;br /&gt;
  product = five.times(3);&lt;br /&gt;
  assertEquals(15, product.amount);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new test won't compile until we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  amount *= multiplier;&lt;br /&gt;
  return null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now the test compiles, but &amp;lt;span style=&amp;quot;color:red&amp;quot;&amp;gt;fails&amp;lt;/span&amp;gt;. Once again, we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  return new Dollar(amount * multiplier);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green Step===&lt;br /&gt;
&lt;br /&gt;
The test &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;succeeds&amp;lt;/span&amp;gt;. So we see that even when we are refactoring we change the test first, then the code. This way we know our refactoring is an improvement.&lt;br /&gt;
&lt;br /&gt;
==More Examples==&lt;br /&gt;
See &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck for more examples.&lt;br /&gt;
&lt;br /&gt;
=Characteristics of a Good Unit Test=&lt;br /&gt;
A good unit test has the following characteristics.&lt;br /&gt;
*It is important that the test executes fast. If the tests are slow, they will not be run often.&lt;br /&gt;
*Environmental dependencies such as databases, file systems, networks, queues, and so on which will slow down the tests are either separated or simulated. Tests that exercise these will not run fast, and a failure does not give meaningful feedback about what the problem actually is.&lt;br /&gt;
*The scope of testing is very limited. If the test fails, it's obvious where to look for the problem. It's important to only test one aspect in a single test.&lt;br /&gt;
*The test should run and pass in isolation (on any machine). If the tests require special environmental setup or fail unexpectedly, then they are not good unit tests.&lt;br /&gt;
*Such a test often uses stubs and mock objects. If the code being tested typically calls out to a database or file system, these dependencies must be simulated, or mocked. These dependencies will ordinarily be abstracted away by using interfaces.&lt;br /&gt;
*The intention of testing is clearly revealed. Another developer can look at the test and understand what is expected of the production code.&lt;br /&gt;
&lt;br /&gt;
=Benefits of TDD=&lt;br /&gt;
&lt;br /&gt;
Using TDD has many benefits.&lt;br /&gt;
&lt;br /&gt;
*Automated testing: Automated system makes the testing much more easier and faster. Manual testing is slower and needs human interaction which is error-prone. Automated testing makes sure any particular test is not missing every time we test the system, whereas humans may leave a test out mistakenly during testing process.&lt;br /&gt;
*Better to test New/Modified Functionality: With manual testing whenever you add new functionality or modify existing functionality, QA personal needs to test all systems that may be affected due to the modification which may be time-consuming. This may also leave a hidden bug in the system after modification. With TDD whenever a new functionality is added or existing functionality is modified, the whole set of tests in the system is run to make sure existing tests are passed. This makes sure that existing functionality is not broken.&lt;br /&gt;
*Developer’s confidence: With TDD, developers are more safe to change the system as any inappropriate changes will make some tests to fail. With non-TDD system developers needs to take more care to change existing system as the new change may fail other functionality. But with TDD developers can do so easily as after modification if developer runs the test he/she will find immediately that the change has failed some other tests (i.e. some other part of the system).&lt;br /&gt;
*Manual testing stage is shortened: In non-TDD development, as soon as developers prepare a build, QA personal starts testing. This manual testing takes a reasonable amount of time and increases the time to deliver the product from the build time. With TDD, a major part of the system is tested during development and needs lesser QA involvement in the time between build and final delivery of the product.&lt;br /&gt;
*Alternative Documentation: Unit tests are kind of documentation to system. Each unit test tells about an individual requirement to the module or system. For example, the following test ensures that only a logged in user with proper balance can buy an item when the item exists in stock. This test reflects a user aspect scenario of the system.&lt;br /&gt;
&lt;br /&gt;
     public void CheckUserCanNotPurchaseItemWithoutBalance(){  &lt;br /&gt;
     LoginToTheSystem();       &lt;br /&gt;
     SelectAnItemToBuy();       &lt;br /&gt;
     MakeSureItemExsitsInStock();       &lt;br /&gt;
     MakeSureUserHasBalanceToBuy();      &lt;br /&gt;
     RunTheTransaction(); &lt;br /&gt;
  }			&lt;br /&gt;
*Better way to fix bugs: In TDD approach when QA finds a bug, developer first writes a test that generates the bug (that is the test will fail due to this bug). Then developer modifies code to make sure that the test is passed (i.e., the bug is fixed). This approach makes sure that next time the bug will not appear in the system as a test is written in the system to take care of the bug.&lt;br /&gt;
*Repetition of the same bug reduced: With TDD once a bug is found, it's put under test. So every time you run the whole test in the system, the tests associated with the bug are run and make sure the bugs are not generated again.&lt;br /&gt;
&lt;br /&gt;
=Shortcomings Of TDD=&lt;br /&gt;
&lt;br /&gt;
TDD has a few shortcomings:&lt;br /&gt;
&lt;br /&gt;
*The actual database or external file is never tested directly by TDD (only production code can test it)&lt;br /&gt;
*If not used carefully, it can add to the total project costs and complexity of the project&lt;br /&gt;
*TDD is unable to test UI.&lt;br /&gt;
*TDD is highly reliant on Refactoring and Programmer Skills.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
&lt;br /&gt;
TDD fundamentaly changes how a developer approaches a programming project. It forces him to focus on the design requirements first by mandating that the developer must write a test for anything before he writes code to do it. It has many benefits including ensuring that the project is well tested and, in some cases, reducing development time. However, it is limited in that it can't test user interfaces or databases directly. Overall, it is a very effective tool for quickly writing well tested code.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
*[http://catalog.lib.ncsu.edu/record/NCSU1601963 Beck, K. (2002). Test-driven development by example. Addison-Wesley.]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Test_driven_development (n.d.). Test-driven development. website: http://en.wikipedia.org/wiki/Test_driven_development]&lt;br /&gt;
*[http://c2.com/cgi/wiki?TestDrivenDevelopment (2012, January 11). Test driven development. website: http://c2.com/cgi/wiki?TestDrivenDevelopment]&lt;br /&gt;
*[http://www.agiledata.org/essays/tdd.html Ambler, S. W. (2002). Introduction to test driven development (tdd). Retrieved from Agile Data website: http://www.agiledata.org/essays/tdd.html]&lt;br /&gt;
*[http://www.methodsandtools.com/archive/archive.php?id=20 Murphy, Craig. (n. d.). Methods and Tools Archives website http://www.methodsandtools.com/archive/archive.php?id=20]&lt;br /&gt;
*[http://www.martinfowler.com/bliki/TestDrivenDevelopment.html www.martinfowler.com/bliki/TestDrivenDevelopment]&lt;br /&gt;
*[http://www.codeproject.com/Articles/47747/Test-Driven-Development-TDD-Step-by-Step-Part-1-In TDD Step by Step Code Project]&lt;br /&gt;
*[http://integralpath.blogs.com/thinkingoutloud/2005/09/principles_of_t.html Principles of Testing]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=69282</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w11 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=69282"/>
		<updated>2012-10-30T01:00:38Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Introduction=&lt;br /&gt;
Test driven development (TDD) is a process that tries to create the minimal amount of code to meet customer's expectations. The idea is to test first, code second, then improve (or [http://en.wikipedia.org/wiki/Refactoring refactor]) last. This process forces the software developers to focus on customer specifications and validation first. Since at each step of the way the programmer proves to himself that the code meets specifications, TDD gives the programmer confidence. The rest of this chapter gives the motivation for TDD, shows the steps for TDD, outlines the principles of TDD, provides examples using TDD, and compares the pros and cons of TDD.&lt;br /&gt;
&lt;br /&gt;
=Motivation for TDD=&lt;br /&gt;
&lt;br /&gt;
There are two main motivations for TDD.&lt;br /&gt;
&lt;br /&gt;
[[File:CostofChange.png|550px|Thumb:Figure 1: Traditional &amp;quot;Cost of Change&amp;quot; curve with the waterfall model superimposed]]&lt;br /&gt;
&lt;br /&gt;
*Testing is the one activity that improves the quality of code. In various design scenarios, like waterfall model, testing occurs towards the end of the project development activity. As shown in the figure 1, introducing testing as a latter phase increases the cost incurred for implementing the changes. From this we infer that there is a high chance of reducing the costs by moving the Test phase to the initial part.&lt;br /&gt;
*The client can also be well informed about the design and can suggest changes which can be incorporated well in advance. This approach also known as TDD helps achieve flexibility to achieve the client’s ever-changing requirements&lt;br /&gt;
&lt;br /&gt;
=Principles=&lt;br /&gt;
&lt;br /&gt;
TDD follows several principles:&lt;br /&gt;
&lt;br /&gt;
*Tests serve as examples of how to use a class or method.  Once used to having tests that show how things work (and that they work), developers start inquiring if a test was already there for the piece of code to be developed&lt;br /&gt;
*Developer tests are distinctly different from QA (Quality Analysis) tests and should be kept separate.  QA tests target features and treat the system as a black box.  Unit tests created by the developer operate at a lower level and test different things.&lt;br /&gt;
*Name the tests carefully.  For Example, name test packages like the package being tested with a suffix.  For example, the &amp;quot;DataAccess&amp;quot; project/package is tested by &amp;quot;DataAccess.Test&amp;quot;. Also,  name test classes the same as the class under test with the suffix &amp;quot;Test&amp;quot;.  For example, the class &amp;quot;PrintManager&amp;quot; is tested by the test class &amp;quot;PrintManagerTest&amp;quot;.  This convention makes it easy to find the related class and keeps the class name a noun. You should also name test methods the same as the method being tested with the prefix &amp;quot;Test&amp;quot;.  For example, the method &amp;quot;PrintProductOrder()&amp;quot; is tested by the method &amp;quot;TestPrintProductOrder()&amp;quot;.  This convention keeps the method name a verb that reads as an english phrase.  &lt;br /&gt;
*Write each test before writing the method under test. It encourages the developer to think as a user of the target method before thinking about implementation, which usually results in a cleaner, easier-to-use interface.&lt;br /&gt;
*Follow the &amp;quot;3-As&amp;quot; pattern for test methods: Arrange, Act, Assert. Specifically, use separate code paragraphs (groups of lines of code separated by a blank line) for each of the As.  Arrange is variable declaration and initialization.  Act is invoking the code under test.  Assert is using the Assert.* methods to verify that expectations were met. &lt;br /&gt;
*When writing application code, only write enough code to make a test work. This technique prevents gold-plating and ensures that you always have a test for the code you write. &lt;br /&gt;
*When you find you need to refractor working code, refractor and re-test prior to writing new code.  This technique ensures your refractoring is correct prior to adding new functionality and applies to creating new methods, introducing inheritance, everything.&lt;br /&gt;
&lt;br /&gt;
=Steps=&lt;br /&gt;
[[File:TDD_Steps.png|550px|Thumb:Figure 1: Traditional &amp;quot;Cost of Change&amp;quot; curve with the waterfall model superimposed]]&lt;br /&gt;
&lt;br /&gt;
Follow these steps:&lt;br /&gt;
*Understand the requirements of the story, work item, or feature that you are working on.&lt;br /&gt;
*Red:Create a test and make it fail.&lt;br /&gt;
Imagine how the new code should be called and write the test as if the code already existed.&lt;br /&gt;
Create the new production code stub. Write just enough code so that it compiles.&lt;br /&gt;
Run the test. It should fail. This is a calibration measure to ensure that your test is calling the correct code and that the code is not working by accident. This is a meaningful failure, and you expect it to fail.&lt;br /&gt;
*Green: Make the test pass by any means necessary.&lt;br /&gt;
Write the production code to make the test pass. Keep it simple.&lt;br /&gt;
Some advocate the hard-coding of the expected return value first to verify that the test correctly detects success. This varies from practitioner to practitioner.If you've written the code so that the test passes as intended, you are finished. You do not have to write more code speculatively. If new functionality is still needed, then another test is needed. Make this one test pass and continue.&lt;br /&gt;
When the test passes, you might want to run all tests up to this point to build confidence that everything else is still working.&lt;br /&gt;
*Refractor: Change the code to remove duplication in your project and to improve the design while ensuring that all tests still pass.&lt;br /&gt;
Remove duplication caused by the addition of the new functionality.&lt;br /&gt;
Make design changes to improve the overall solution.&lt;br /&gt;
After each refactoring, rerun all the tests to ensure that they all still pass.&lt;br /&gt;
*Repeat the cycle. Each cycle should be very short, and a typical hour should contain many Red/Green/ Refractor cycles.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
&lt;br /&gt;
==Homework Grades Program==&lt;br /&gt;
&lt;br /&gt;
===Setup===&lt;br /&gt;
As a simple example, we are creating a program that keeps track of our homework grades. We envision that we would be able to get the average of these homework grades. Step one: &amp;lt;b&amp;gt; write a test &amp;lt;/b&amp;gt;. Let's test an average function&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We will get multiple errors - this test won't even compile (but, that's ok for now). Let's take a look at what will generate error messages:&lt;br /&gt;
&lt;br /&gt;
* class &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; constructor not declared&lt;br /&gt;
* field &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* method &amp;lt;code&amp;gt;average&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
&lt;br /&gt;
Now, we fix the first error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Second error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Homework(void) {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Third error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int * grades;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fourth error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int average(int * grades) {&lt;br /&gt;
  return 0; // default return value&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, the test compiles! The code now looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
&lt;br /&gt;
    return 0; // default return value&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
Now, we run the test, and the familar red bar of failure greets us (remember the mantra red-green-refactor). The assert fails. The average function needs to actually average something (not just return 0). As we think about averaging the grades, we realize we need to know how many grades are in the int array &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt;. So, we add to the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
  int numGrades;                         // new&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
 &lt;br /&gt;
   int avg = 0;                         // new&lt;br /&gt;
 &lt;br /&gt;
   for(int i = 0; i &amp;lt; numGrades; i++) { // new&lt;br /&gt;
     avg += grades[i];                  // new&lt;br /&gt;
   }                                    // new&lt;br /&gt;
 &lt;br /&gt;
   return avg/numGrades;                // new&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Of course, we must remember to change the test to:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  myHomework.numGrades = 2;&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
Success! We have a green bar when we run it. &lt;br /&gt;
&lt;br /&gt;
===Refactor===&lt;br /&gt;
The last step is refactoring. Perhaps we don't want a grade to be an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;? Should it be an &amp;lt;code&amp;gt;unsigned int&amp;lt;/code&amp;gt;? For this simple example, there isn't much refactoring to do, but in a larger example there may be multiple areas for improvement.&lt;br /&gt;
&lt;br /&gt;
==Refactoring Example==&lt;br /&gt;
The following example is take from &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck.&lt;br /&gt;
&lt;br /&gt;
Using the TDD process the author created an object with the following structure:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dollar {&lt;br /&gt;
 &lt;br /&gt;
  Dollar(int amount) {&lt;br /&gt;
     this.amount = amount;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  void times(int mulitplier) {&lt;br /&gt;
    amount *= multiplier;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
What's wrong with the code above? Look at the following test:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  &lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  five.times(2);&lt;br /&gt;
  assertEquals(10, five.amount);&lt;br /&gt;
  five.times(3);&lt;br /&gt;
  assertEquals(15, five.amount);&lt;br /&gt;
&lt;br /&gt;
}  &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Whenever we perform an operation on a &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; the value of the &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; changes. In the test above &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; isn't 5 after we multiply it by 2, and thus the name &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; doesn't make sense anymore. How do we change this? &lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
&lt;br /&gt;
First, we change the &amp;lt;b&amp;gt;test&amp;lt;/b&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  Dollar product = five.times(2);&lt;br /&gt;
  assertEquals(10, product.amount);&lt;br /&gt;
  product = five.times(3);&lt;br /&gt;
  assertEquals(15, product.amount);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new test won't compile until we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  amount *= multiplier;&lt;br /&gt;
  return null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now the test compiles, but fails. Once again, we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  return new Dollar(amount * multiplier);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
&lt;br /&gt;
The test succeeds. So we see that even when we are refactoring we change the test first, then the code. This way we know our refactoring is an improvement.&lt;br /&gt;
&lt;br /&gt;
==More Examples==&lt;br /&gt;
See &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck for more examples.&lt;br /&gt;
&lt;br /&gt;
=Characteristics Of A Good Unit Test=&lt;br /&gt;
A good unit test has the following characteristics.&lt;br /&gt;
*It is important that the test executes fast. If the tests are slow, they will not be run often.&lt;br /&gt;
*Environmental dependencies such as databases, file systems, networks, queues, and so on which will slow down the tests are either separated or simulated. Tests that exercise these will not run fast, and a failure does not give meaningful feedback about what the problem actually is.&lt;br /&gt;
*The scope of testing is very limited. If the test fails, it's obvious where to look for the problem. It's important to only test one aspect in a single test.&lt;br /&gt;
*The test should run and pass in isolation (on any machine). If the tests require special environmental setup or fail unexpectedly, then they are not good unit tests.&lt;br /&gt;
*Such a test often uses stubs and mock objects. If the code being tested typically calls out to a database or file system, these dependencies must be simulated, or mocked. These dependencies will ordinarily be abstracted away by using interfaces.&lt;br /&gt;
*The intention of testing is clearly revealed. Another developer can look at the test and understand what is expected of the production code.&lt;br /&gt;
&lt;br /&gt;
=Benefits Of TDD=&lt;br /&gt;
&lt;br /&gt;
Using TDD has many benefits.&lt;br /&gt;
&lt;br /&gt;
*Automated testing: Automated system makes the testing much more easier and faster. Manual testing is slower and needs human interaction which is error-prone. Automated testing makes sure any particular test is not missing every time we test the system, whereas humans may leave a test out mistakenly during testing process.&lt;br /&gt;
*Better to test New/Modified Functionality: With manual testing whenever you add new functionality or modify existing functionality, QA personal needs to test all systems that may be affected due to the modification which may be time-consuming. This may also leave a hidden bug in the system after modification. With TDD whenever a new functionality is added or existing functionality is modified, the whole set of tests in the system is run to make sure existing tests are passed. This makes sure that existing functionality is not broken.&lt;br /&gt;
*Developer’s confidence: With TDD, developers are more safe to change the system as any inappropriate changes will make some tests to fail. With non-TDD system developers needs to take more care to change existing system as the new change may fail other functionality. But with TDD developers can do so easily as after modification if developer runs the test he/she will find immediately that the change has failed some other tests (i.e. some other part of the system).&lt;br /&gt;
*Manual testing stage is shortened: In non-TDD development, as soon as developers prepare a build, QA personal starts testing. This manual testing takes a reasonable amount of time and increases the time to deliver the product from the build time. With TDD, a major part of the system is tested during development and needs lesser QA involvement in the time between build and final delivery of the product.&lt;br /&gt;
*Alternative Documentation: Unit tests are kind of documentation to system. Each unit test tells about an individual requirement to the module or system. For example, the following test ensures that only a logged in user with proper balance can buy an item when the item exists in stock. This test reflects a user aspect scenario of the system.&lt;br /&gt;
&lt;br /&gt;
     public void CheckUserCanNotPurchaseItemWithoutBalance(){  &lt;br /&gt;
     LoginToTheSystem();       &lt;br /&gt;
     SelectAnItemToBuy();       &lt;br /&gt;
     MakeSureItemExsitsInStock();       &lt;br /&gt;
     MakeSureUserHasBalanceToBuy();      &lt;br /&gt;
     RunTheTransaction(); &lt;br /&gt;
  }			&lt;br /&gt;
*Better way to fix bugs: In TDD approach when QA finds a bug, developer first writes a test that generates the bug (that is the test will fail due to this bug). Then developer modifies code to make sure that the test is passed (i.e., the bug is fixed). This approach makes sure that next time the bug will not appear in the system as a test is written in the system to take care of the bug.&lt;br /&gt;
*Repetition of the same bug reduced: With TDD once a bug is found, it's put under test. So every time you run the whole test in the system, the tests associated with the bug are run and make sure the bugs are not generated again.&lt;br /&gt;
&lt;br /&gt;
=Shortcomings Of TDD=&lt;br /&gt;
&lt;br /&gt;
TDD has a few shortcomings:&lt;br /&gt;
&lt;br /&gt;
*The actual database or external file is never tested directly by TDD (only production code can test it)&lt;br /&gt;
*If not used carefully, it can add to the total project costs and complexity of the project&lt;br /&gt;
*TDD is unable to test UI.&lt;br /&gt;
*TDD is highly reliant on Refactoring and Programmer Skills.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
&lt;br /&gt;
TDD fundamentaly changes how a developer approaches a programming project. It forces him to focus on the design requirements first by mandating that the developer must write a test for anything before he writes code to do it. It has many benefits including ensuring that the project is well tested and, in some cases, reducing development time. However, it is limited in that it can't test user interfaces or databases directly. TDD is a component of [http://en.wikipedia.org/wiki/Extreme_programming Extreme Programming] and often used in conjunction with integration tests. Overall, it is a very effective tool for quickly writing well tested code.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
*[http://catalog.lib.ncsu.edu/record/NCSU1601963 Beck, K. (2002). Test-driven development by example. Addison-Wesley.]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Test_driven_development (n.d.). Test-driven development. website: http://en.wikipedia.org/wiki/Test_driven_development]&lt;br /&gt;
*[http://c2.com/cgi/wiki?TestDrivenDevelopment (2012, January 11). Test driven development. website: http://c2.com/cgi/wiki?TestDrivenDevelopment]&lt;br /&gt;
*[http://www.agiledata.org/essays/tdd.html Ambler, S. W. (2002). Introduction to test driven development (tdd). Retrieved from Agile Data website: http://www.agiledata.org/essays/tdd.html]&lt;br /&gt;
*[http://www.methodsandtools.com/archive/archive.php?id=20. Methods and Tools Archives]&lt;br /&gt;
*[http://www.martinfowler.com/bliki/TestDrivenDevelopment.html www.martinfowler.com/bliki/TestDrivenDevelopment]&lt;br /&gt;
*[http://www.codeproject.com/Articles/47747/Test-Driven-Development-TDD-Step-by-Step-Part-1-In TDD Step by Step Code Project]&lt;br /&gt;
*[http://integralpath.blogs.com/thinkingoutloud/2005/09/principles_of_t.html Principles of Testing]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=68184</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w11 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=68184"/>
		<updated>2012-10-25T17:02:56Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Conclusion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Introduction=&lt;br /&gt;
Test driven development (TDD) is a process that tries to create the minimal amount of code to meet customer's expectations. The idea is to test first, code second, then improve (or refactor) last. This process forces the software developers to focus on customer specifications and validation first. Since at each step of the way the programmer proves to himself that the code meets specifications, TDD gives the programmer confidence. The rest of this chapter gives the motivation for TDD, shows the steps for TDD, outlines the principles of TDD, provides examples using TDD, and compares the pros and cons of TDD.&lt;br /&gt;
&lt;br /&gt;
=Motivation for TDD=&lt;br /&gt;
&lt;br /&gt;
There are two main motivations for TDD.&lt;br /&gt;
&lt;br /&gt;
[[File:TimevsCostDev.png|350px|Thumb:Figure 1: Traditional &amp;quot;Cost of Change&amp;quot; curve with the waterfall model superimposed]]&lt;br /&gt;
&lt;br /&gt;
*Testing is the one activity that improves the quality of code. In various design scenarios, like waterfall model, testing occurs towards the end of the project development activity. As shown in the figure 1, introducing testing as a latter phase increases the cost incurred for implementing the changes. From this we infer that there is a high chance of reducing the costs by moving the Test phase to the initial part.&lt;br /&gt;
*The client can also be well informed about the design and can suggest changes which can be incorporated well in advance. This approach also known as TDD helps achieve flexibility to achieve the client’s ever-changing requirements&lt;br /&gt;
&lt;br /&gt;
=Principles=&lt;br /&gt;
&lt;br /&gt;
TDD follows several principles:&lt;br /&gt;
&lt;br /&gt;
*Tests serve as examples of how to use a class or method.  Once used to having tests that show how things work (and that they work), developers start inquiring if a test was already there for the piece of code to be developed&lt;br /&gt;
*Developer tests are distinctly different from QA (Quality Analysis) tests and should be kept separate.  QA tests target features and treat the system as a black box.  Unit tests created by the developer operate at a lower level and test different things.&lt;br /&gt;
*Name the tests carefully.  For Example, name test packages like the package being tested with a suffix.  For example, the &amp;quot;DataAccess&amp;quot; project/package is tested by &amp;quot;DataAccess.Test&amp;quot;. Also,  name test classes the same as the class under test with the suffix &amp;quot;Test&amp;quot;.  For example, the class &amp;quot;PrintManager&amp;quot; is tested by the test class &amp;quot;PrintManagerTest&amp;quot;.  This convention makes it easy to find the related class and keeps the class name a noun. You should also name test methods the same as the method being tested with the prefix &amp;quot;Test&amp;quot;.  For example, the method &amp;quot;PrintProductOrder()&amp;quot; is tested by the method &amp;quot;TestPrintProductOrder()&amp;quot;.  This convention keeps the method name a verb that reads as an english phrase.  &lt;br /&gt;
*Write each test before writing the method under test. It encourages the developer to think as a user of the target method before thinking about implementation, which usually results in a cleaner, easier-to-use interface.&lt;br /&gt;
*Follow the &amp;quot;3-As&amp;quot; pattern for test methods: Arrange, Act, Assert. Specifically, use separate code paragraphs (groups of lines of code separated by a blank line) for each of the As.  Arrange is variable declaration and initialization.  Act is invoking the code under test.  Assert is using the Assert.* methods to verify that expectations were met. &lt;br /&gt;
*When writing application code, only write enough code to make a test work. This technique prevents gold-plating and ensures that you always have a test for the code you write. &lt;br /&gt;
*When you find you need to refractor working code, refractor and re-test prior to writing new code.  This technique ensures your refractoring is correct prior to adding new functionality and applies to creating new methods, introducing inheritance, everything.&lt;br /&gt;
&lt;br /&gt;
=Steps=&lt;br /&gt;
&lt;br /&gt;
[[Image:PureFab.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Follow these steps:&lt;br /&gt;
*Understand the requirements of the story, work item, or feature that you are working on.&lt;br /&gt;
*Red:Create a test and make it fail.&lt;br /&gt;
Imagine how the new code should be called and write the test as if the code already existed.&lt;br /&gt;
Create the new production code stub. Write just enough code so that it compiles.&lt;br /&gt;
Run the test. It should fail. This is a calibration measure to ensure that your test is calling the correct code and that the code is not working by accident. This is a meaningful failure, and you expect it to fail.&lt;br /&gt;
*Green: Make the test pass by any means necessary.&lt;br /&gt;
Write the production code to make the test pass. Keep it simple.&lt;br /&gt;
Some advocate the hard-coding of the expected return value first to verify that the test correctly detects success. This varies from practitioner to practitioner.If you've written the code so that the test passes as intended, you are finished. You do not have to write more code speculatively. If new functionality is still needed, then another test is needed. Make this one test pass and continue.&lt;br /&gt;
When the test passes, you might want to run all tests up to this point to build confidence that everything else is still working.&lt;br /&gt;
*Refractor: Change the code to remove duplication in your project and to improve the design while ensuring that all tests still pass.&lt;br /&gt;
Remove duplication caused by the addition of the new functionality.&lt;br /&gt;
Make design changes to improve the overall solution.&lt;br /&gt;
After each refactoring, rerun all the tests to ensure that they all still pass.&lt;br /&gt;
*Repeat the cycle. Each cycle should be very short, and a typical hour should contain many Red/Green/ Refractor cycles.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
&lt;br /&gt;
==Homework Grades Program==&lt;br /&gt;
&lt;br /&gt;
===Setup===&lt;br /&gt;
As a simple example, we are creating a program that keeps track of our homework grades. We envision that we would be able to get the average of these homework grades. Step one: &amp;lt;b&amp;gt; write a test &amp;lt;/b&amp;gt;. Let's test an average function&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We will get multiple errors - this test won't even compile (but, that's ok for now). Let's take a look at what will generate error messages:&lt;br /&gt;
&lt;br /&gt;
* class &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; constructor not declared&lt;br /&gt;
* field &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* method &amp;lt;code&amp;gt;average&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
&lt;br /&gt;
Now, we fix the first error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Second error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Homework(void) {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Third error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int * grades;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fourth error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int average(int * grades) {&lt;br /&gt;
  return 0; // default return value&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, the test compiles! The code now looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
&lt;br /&gt;
    return 0; // default return value&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
Now, we run the test, and the familar red bar of failure greets us (remember the mantra red-green-refactor). The assert fails. The average function needs to actually average something (not just return 0). As we think about averaging the grades, we realize we need to know how many grades are in the int array &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt;. So, we add to the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
  int numGrades;                         // new&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
 &lt;br /&gt;
   int avg = 0;                         // new&lt;br /&gt;
 &lt;br /&gt;
   for(int i = 0; i &amp;lt; numGrades; i++) { // new&lt;br /&gt;
     avg += grades[i];                  // new&lt;br /&gt;
   }                                    // new&lt;br /&gt;
 &lt;br /&gt;
   return avg/numGrades;                // new&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Of course, we must remember to change the test to:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  myHomework.numGrades = 2;&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
Success! We have a green bar when we run it. &lt;br /&gt;
&lt;br /&gt;
===Refactor===&lt;br /&gt;
The last step is refactoring. Perhaps we don't want a grade to be an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;? Should it be an &amp;lt;code&amp;gt;unsigned int&amp;lt;/code&amp;gt;? For this simple example, there isn't much refactoring to do, but in a larger example there may be multiple areas for improvement.&lt;br /&gt;
&lt;br /&gt;
==Refactoring Example==&lt;br /&gt;
The following example is take from &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck.&lt;br /&gt;
&lt;br /&gt;
Using the TDD process the author created an object with the following structure:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dollar {&lt;br /&gt;
 &lt;br /&gt;
  Dollar(int amount) {&lt;br /&gt;
     this.amount = amount;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  void times(int mulitplier) {&lt;br /&gt;
    amount *= multiplier;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
What's wrong with the code above? Look at the following test:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  &lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  five.times(2);&lt;br /&gt;
  assertEquals(10, five.amount);&lt;br /&gt;
  five.times(3);&lt;br /&gt;
  assertEquals(15, five.amount);&lt;br /&gt;
&lt;br /&gt;
}  &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Whenever we perform an operation on a &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; the value of the &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; changes. In the test above &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; isn't 5 after we multiply it by 2, and thus the name &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; doesn't make sense anymore. How do we change this? &lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
&lt;br /&gt;
First, we change the &amp;lt;b&amp;gt;test&amp;lt;/b&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  Dollar product = five.times(2);&lt;br /&gt;
  assertEquals(10, product.amount);&lt;br /&gt;
  product = five.times(3);&lt;br /&gt;
  assertEquals(15, product.amount);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new test won't compile until we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  amount *= multiplier;&lt;br /&gt;
  return null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now the test compiles, but fails. Once again, we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  return new Dollar(amount * multiplier);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
&lt;br /&gt;
The test succeeds. So we see that even when we are refactoring we change the test first, then the code. This way we know our refactoring is an improvement.&lt;br /&gt;
&lt;br /&gt;
==More Examples==&lt;br /&gt;
See &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck for more examples.&lt;br /&gt;
&lt;br /&gt;
=Characteristics Of A Good Unit Test=&lt;br /&gt;
A good unit test has the following characteristics.&lt;br /&gt;
*It is important that the test executes fast. If the tests are slow, they will not be run often.&lt;br /&gt;
*Environmental dependencies such as databases, file systems, networks, queues, and so on which will slow down the tests are either separated or simulated. Tests that exercise these will not run fast, and a failure does not give meaningful feedback about what the problem actually is.&lt;br /&gt;
*The scope of testing is very limited. If the test fails, it's obvious where to look for the problem. It's important to only test one aspect in a single test.&lt;br /&gt;
*The test should run and pass in isolation (on any machine). If the tests require special environmental setup or fail unexpectedly, then they are not good unit tests.&lt;br /&gt;
*Such a test often uses stubs and mock objects. If the code being tested typically calls out to a database or file system, these dependencies must be simulated, or mocked. These dependencies will ordinarily be abstracted away by using interfaces.&lt;br /&gt;
*The intention of testing is clearly revealed. Another developer can look at the test and understand what is expected of the production code.&lt;br /&gt;
&lt;br /&gt;
=Benefits Of TDD=&lt;br /&gt;
&lt;br /&gt;
Using TDD has many benefits.&lt;br /&gt;
&lt;br /&gt;
*Automated testing: Automated system makes the testing much more easier and faster. Manual testing is slower and needs human interaction which is error-prone. Automated testing makes sure any particular test is not missing every time we test the system, whereas humans may leave a test out mistakenly during testing process.&lt;br /&gt;
*Better to test New/Modified Functionality: With manual testing whenever you add new functionality or modify existing functionality, QA personal needs to test all systems that may be affected due to the modification which may be time-consuming. This may also leave a hidden bug in the system after modification. With TDD whenever a new functionality is added or existing functionality is modified, the whole set of tests in the system is run to make sure existing tests are passed. This makes sure that existing functionality is not broken.&lt;br /&gt;
*Developer’s confidence: With TDD, developers are more safe to change the system as any inappropriate changes will make some tests to fail. With non-TDD system developers needs to take more care to change existing system as the new change may fail other functionality. But with TDD developers can do so easily as after modification if developer runs the test he/she will find immediately that the change has failed some other tests (i.e. some other part of the system).&lt;br /&gt;
*Manual testing stage is shortened: In non-TDD development, as soon as developers prepare a build, QA personal starts testing. This manual testing takes a reasonable amount of time and increases the time to deliver the product from the build time. With TDD, a major part of the system is tested during development and needs lesser QA involvement in the time between build and final delivery of the product.&lt;br /&gt;
*Alternative Documentation: Unit tests are kind of documentation to system. Each unit test tells about an individual requirement to the module or system. For example, the following test ensures that only a logged in user with proper balance can buy an item when the item exists in stock. This test reflects a user aspect scenario of the system.&lt;br /&gt;
&lt;br /&gt;
     public void CheckUserCanNotPurchaseItemWithoutBalance(){  &lt;br /&gt;
     LoginToTheSystem();       &lt;br /&gt;
     SelectAnItemToBuy();       &lt;br /&gt;
     MakeSureItemExsitsInStock();       &lt;br /&gt;
     MakeSureUserHasBalanceToBuy();      &lt;br /&gt;
     RunTheTransaction(); &lt;br /&gt;
  }			&lt;br /&gt;
*Better way to fix bugs: In TDD approach when QA finds a bug, developer first writes a test that generates the bug (that is the test will fail due to this bug). Then developer modifies code to make sure that the test is passed (i.e., the bug is fixed). This approach makes sure that next time the bug will not appear in the system as a test is written in the system to take care of the bug.&lt;br /&gt;
*Repetition of the same bug reduced: With TDD once a bug is found, it's put under test. So every time you run the whole test in the system, the tests associated with the bug are run and make sure the bugs are not generated again.&lt;br /&gt;
&lt;br /&gt;
=Shortcomings Of TDD=&lt;br /&gt;
&lt;br /&gt;
TDD has a few shortcomings:&lt;br /&gt;
&lt;br /&gt;
*The actual database or external file is never tested directly by TDD (only production code can test it)&lt;br /&gt;
*If not used carefully, it can add to the total project costs and complexity of the project&lt;br /&gt;
*TDD is unable to test UI.&lt;br /&gt;
*TDD is highly reliant on Refactoring and Programmer Skills.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
&lt;br /&gt;
TDD fundamentaly changes how a developer approaches a programming project. It forces him to focus on the design requirements first by mandating that the developer must write a test for anything before he writes code to do it. It has many benefits including ensuring that the project is well tested and, in some cases, reducing development time. However, it is limited in that it can't test user interfaces or databases directly. TDD is a component of [http://en.wikipedia.org/wiki/Extreme_programming Extreme Programming] and often used in conjunction with integration tests. Overall, it is a very effective tool for quickly writing well tested code.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
*[http://catalog.lib.ncsu.edu/record/NCSU1601963 Beck, K. (2002). Test-driven development by example. Addison-Wesley.]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Test_driven_development (n.d.). Test-driven development. website: http://en.wikipedia.org/wiki/Test_driven_development]&lt;br /&gt;
*[http://c2.com/cgi/wiki?TestDrivenDevelopment (2012, January 11). Test driven development. website: http://c2.com/cgi/wiki?TestDrivenDevelopment]&lt;br /&gt;
*[http://www.agiledata.org/essays/tdd.html Ambler, S. W. (2002). Introduction to test driven development (tdd). Retrieved from Agile Data website: http://www.agiledata.org/essays/tdd.html]&lt;br /&gt;
*[http://www.methodsandtools.com/archive/archive.php?id=20. Methods and Tools Archives]&lt;br /&gt;
*[http://www.martinfowler.com/bliki/TestDrivenDevelopment.html www.martinfowler.com/bliki/TestDrivenDevelopment]&lt;br /&gt;
*[http://www.codeproject.com/Articles/47747/Test-Driven-Development-TDD-Step-by-Step-Part-1-In TDD Step by Step Code Project]&lt;br /&gt;
*[http://integralpath.blogs.com/thinkingoutloud/2005/09/principles_of_t.html Principles of Testing]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=68183</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w11 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=68183"/>
		<updated>2012-10-25T16:57:40Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Shortcomings Of TDD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Introduction=&lt;br /&gt;
Test driven development (TDD) is a process that tries to create the minimal amount of code to meet customer's expectations. The idea is to test first, code second, then improve (or refactor) last. This process forces the software developers to focus on customer specifications and validation first. Since at each step of the way the programmer proves to himself that the code meets specifications, TDD gives the programmer confidence. The rest of this chapter gives the motivation for TDD, shows the steps for TDD, outlines the principles of TDD, provides examples using TDD, and compares the pros and cons of TDD.&lt;br /&gt;
&lt;br /&gt;
=Motivation for TDD=&lt;br /&gt;
&lt;br /&gt;
There are two main motivations for TDD.&lt;br /&gt;
&lt;br /&gt;
[[File:TimevsCostDev.png|350px|Thumb:Figure 1: Traditional &amp;quot;Cost of Change&amp;quot; curve with the waterfall model superimposed]]&lt;br /&gt;
&lt;br /&gt;
*Testing is the one activity that improves the quality of code. In various design scenarios, like waterfall model, testing occurs towards the end of the project development activity. As shown in the figure 1, introducing testing as a latter phase increases the cost incurred for implementing the changes. From this we infer that there is a high chance of reducing the costs by moving the Test phase to the initial part.&lt;br /&gt;
*The client can also be well informed about the design and can suggest changes which can be incorporated well in advance. This approach also known as TDD helps achieve flexibility to achieve the client’s ever-changing requirements&lt;br /&gt;
&lt;br /&gt;
=Principles=&lt;br /&gt;
&lt;br /&gt;
TDD follows several principles:&lt;br /&gt;
&lt;br /&gt;
*Tests serve as examples of how to use a class or method.  Once used to having tests that show how things work (and that they work), developers start inquiring if a test was already there for the piece of code to be developed&lt;br /&gt;
*Developer tests are distinctly different from QA (Quality Analysis) tests and should be kept separate.  QA tests target features and treat the system as a black box.  Unit tests created by the developer operate at a lower level and test different things.&lt;br /&gt;
*Name the tests carefully.  For Example, name test packages like the package being tested with a suffix.  For example, the &amp;quot;DataAccess&amp;quot; project/package is tested by &amp;quot;DataAccess.Test&amp;quot;. Also,  name test classes the same as the class under test with the suffix &amp;quot;Test&amp;quot;.  For example, the class &amp;quot;PrintManager&amp;quot; is tested by the test class &amp;quot;PrintManagerTest&amp;quot;.  This convention makes it easy to find the related class and keeps the class name a noun. You should also name test methods the same as the method being tested with the prefix &amp;quot;Test&amp;quot;.  For example, the method &amp;quot;PrintProductOrder()&amp;quot; is tested by the method &amp;quot;TestPrintProductOrder()&amp;quot;.  This convention keeps the method name a verb that reads as an english phrase.  &lt;br /&gt;
*Write each test before writing the method under test. It encourages the developer to think as a user of the target method before thinking about implementation, which usually results in a cleaner, easier-to-use interface.&lt;br /&gt;
*Follow the &amp;quot;3-As&amp;quot; pattern for test methods: Arrange, Act, Assert. Specifically, use separate code paragraphs (groups of lines of code separated by a blank line) for each of the As.  Arrange is variable declaration and initialization.  Act is invoking the code under test.  Assert is using the Assert.* methods to verify that expectations were met. &lt;br /&gt;
*When writing application code, only write enough code to make a test work. This technique prevents gold-plating and ensures that you always have a test for the code you write. &lt;br /&gt;
*When you find you need to refractor working code, refractor and re-test prior to writing new code.  This technique ensures your refractoring is correct prior to adding new functionality and applies to creating new methods, introducing inheritance, everything.&lt;br /&gt;
&lt;br /&gt;
=Steps=&lt;br /&gt;
&lt;br /&gt;
[[Image:PureFab.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Follow these steps:&lt;br /&gt;
*Understand the requirements of the story, work item, or feature that you are working on.&lt;br /&gt;
*Red:Create a test and make it fail.&lt;br /&gt;
Imagine how the new code should be called and write the test as if the code already existed.&lt;br /&gt;
Create the new production code stub. Write just enough code so that it compiles.&lt;br /&gt;
Run the test. It should fail. This is a calibration measure to ensure that your test is calling the correct code and that the code is not working by accident. This is a meaningful failure, and you expect it to fail.&lt;br /&gt;
*Green: Make the test pass by any means necessary.&lt;br /&gt;
Write the production code to make the test pass. Keep it simple.&lt;br /&gt;
Some advocate the hard-coding of the expected return value first to verify that the test correctly detects success. This varies from practitioner to practitioner.If you've written the code so that the test passes as intended, you are finished. You do not have to write more code speculatively. If new functionality is still needed, then another test is needed. Make this one test pass and continue.&lt;br /&gt;
When the test passes, you might want to run all tests up to this point to build confidence that everything else is still working.&lt;br /&gt;
*Refractor: Change the code to remove duplication in your project and to improve the design while ensuring that all tests still pass.&lt;br /&gt;
Remove duplication caused by the addition of the new functionality.&lt;br /&gt;
Make design changes to improve the overall solution.&lt;br /&gt;
After each refactoring, rerun all the tests to ensure that they all still pass.&lt;br /&gt;
*Repeat the cycle. Each cycle should be very short, and a typical hour should contain many Red/Green/ Refractor cycles.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
&lt;br /&gt;
==Homework Grades Program==&lt;br /&gt;
&lt;br /&gt;
===Setup===&lt;br /&gt;
As a simple example, we are creating a program that keeps track of our homework grades. We envision that we would be able to get the average of these homework grades. Step one: &amp;lt;b&amp;gt; write a test &amp;lt;/b&amp;gt;. Let's test an average function&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We will get multiple errors - this test won't even compile (but, that's ok for now). Let's take a look at what will generate error messages:&lt;br /&gt;
&lt;br /&gt;
* class &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; constructor not declared&lt;br /&gt;
* field &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* method &amp;lt;code&amp;gt;average&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
&lt;br /&gt;
Now, we fix the first error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Second error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Homework(void) {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Third error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int * grades;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fourth error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int average(int * grades) {&lt;br /&gt;
  return 0; // default return value&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, the test compiles! The code now looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
&lt;br /&gt;
    return 0; // default return value&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
Now, we run the test, and the familar red bar of failure greets us (remember the mantra red-green-refactor). The assert fails. The average function needs to actually average something (not just return 0). As we think about averaging the grades, we realize we need to know how many grades are in the int array &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt;. So, we add to the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
  int numGrades;                         // new&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
 &lt;br /&gt;
   int avg = 0;                         // new&lt;br /&gt;
 &lt;br /&gt;
   for(int i = 0; i &amp;lt; numGrades; i++) { // new&lt;br /&gt;
     avg += grades[i];                  // new&lt;br /&gt;
   }                                    // new&lt;br /&gt;
 &lt;br /&gt;
   return avg/numGrades;                // new&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Of course, we must remember to change the test to:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  myHomework.numGrades = 2;&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
Success! We have a green bar when we run it. &lt;br /&gt;
&lt;br /&gt;
===Refactor===&lt;br /&gt;
The last step is refactoring. Perhaps we don't want a grade to be an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;? Should it be an &amp;lt;code&amp;gt;unsigned int&amp;lt;/code&amp;gt;? For this simple example, there isn't much refactoring to do, but in a larger example there may be multiple areas for improvement.&lt;br /&gt;
&lt;br /&gt;
==Refactoring Example==&lt;br /&gt;
The following example is take from &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck.&lt;br /&gt;
&lt;br /&gt;
Using the TDD process the author created an object with the following structure:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dollar {&lt;br /&gt;
 &lt;br /&gt;
  Dollar(int amount) {&lt;br /&gt;
     this.amount = amount;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  void times(int mulitplier) {&lt;br /&gt;
    amount *= multiplier;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
What's wrong with the code above? Look at the following test:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  &lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  five.times(2);&lt;br /&gt;
  assertEquals(10, five.amount);&lt;br /&gt;
  five.times(3);&lt;br /&gt;
  assertEquals(15, five.amount);&lt;br /&gt;
&lt;br /&gt;
}  &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Whenever we perform an operation on a &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; the value of the &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; changes. In the test above &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; isn't 5 after we multiply it by 2, and thus the name &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; doesn't make sense anymore. How do we change this? &lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
&lt;br /&gt;
First, we change the &amp;lt;b&amp;gt;test&amp;lt;/b&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  Dollar product = five.times(2);&lt;br /&gt;
  assertEquals(10, product.amount);&lt;br /&gt;
  product = five.times(3);&lt;br /&gt;
  assertEquals(15, product.amount);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new test won't compile until we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  amount *= multiplier;&lt;br /&gt;
  return null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now the test compiles, but fails. Once again, we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  return new Dollar(amount * multiplier);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
&lt;br /&gt;
The test succeeds. So we see that even when we are refactoring we change the test first, then the code. This way we know our refactoring is an improvement.&lt;br /&gt;
&lt;br /&gt;
==More Examples==&lt;br /&gt;
See &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck for more examples.&lt;br /&gt;
&lt;br /&gt;
=Characteristics Of A Good Unit Test=&lt;br /&gt;
A good unit test has the following characteristics.&lt;br /&gt;
*It is important that the test executes fast. If the tests are slow, they will not be run often.&lt;br /&gt;
*Environmental dependencies such as databases, file systems, networks, queues, and so on which will slow down the tests are either separated or simulated. Tests that exercise these will not run fast, and a failure does not give meaningful feedback about what the problem actually is.&lt;br /&gt;
*The scope of testing is very limited. If the test fails, it's obvious where to look for the problem. It's important to only test one aspect in a single test.&lt;br /&gt;
*The test should run and pass in isolation (on any machine). If the tests require special environmental setup or fail unexpectedly, then they are not good unit tests.&lt;br /&gt;
*Such a test often uses stubs and mock objects. If the code being tested typically calls out to a database or file system, these dependencies must be simulated, or mocked. These dependencies will ordinarily be abstracted away by using interfaces.&lt;br /&gt;
*The intention of testing is clearly revealed. Another developer can look at the test and understand what is expected of the production code.&lt;br /&gt;
&lt;br /&gt;
=Benefits Of TDD=&lt;br /&gt;
&lt;br /&gt;
Using TDD has many benefits.&lt;br /&gt;
&lt;br /&gt;
*Automated testing: Automated system makes the testing much more easier and faster. Manual testing is slower and needs human interaction which is error-prone. Automated testing makes sure any particular test is not missing every time we test the system, whereas humans may leave a test out mistakenly during testing process.&lt;br /&gt;
*Better to test New/Modified Functionality: With manual testing whenever you add new functionality or modify existing functionality, QA personal needs to test all systems that may be affected due to the modification which may be time-consuming. This may also leave a hidden bug in the system after modification. With TDD whenever a new functionality is added or existing functionality is modified, the whole set of tests in the system is run to make sure existing tests are passed. This makes sure that existing functionality is not broken.&lt;br /&gt;
*Developer’s confidence: With TDD, developers are more safe to change the system as any inappropriate changes will make some tests to fail. With non-TDD system developers needs to take more care to change existing system as the new change may fail other functionality. But with TDD developers can do so easily as after modification if developer runs the test he/she will find immediately that the change has failed some other tests (i.e. some other part of the system).&lt;br /&gt;
*Manual testing stage is shortened: In non-TDD development, as soon as developers prepare a build, QA personal starts testing. This manual testing takes a reasonable amount of time and increases the time to deliver the product from the build time. With TDD, a major part of the system is tested during development and needs lesser QA involvement in the time between build and final delivery of the product.&lt;br /&gt;
*Alternative Documentation: Unit tests are kind of documentation to system. Each unit test tells about an individual requirement to the module or system. For example, the following test ensures that only a logged in user with proper balance can buy an item when the item exists in stock. This test reflects a user aspect scenario of the system.&lt;br /&gt;
&lt;br /&gt;
     public void CheckUserCanNotPurchaseItemWithoutBalance(){  &lt;br /&gt;
     LoginToTheSystem();       &lt;br /&gt;
     SelectAnItemToBuy();       &lt;br /&gt;
     MakeSureItemExsitsInStock();       &lt;br /&gt;
     MakeSureUserHasBalanceToBuy();      &lt;br /&gt;
     RunTheTransaction(); &lt;br /&gt;
  }			&lt;br /&gt;
*Better way to fix bugs: In TDD approach when QA finds a bug, developer first writes a test that generates the bug (that is the test will fail due to this bug). Then developer modifies code to make sure that the test is passed (i.e., the bug is fixed). This approach makes sure that next time the bug will not appear in the system as a test is written in the system to take care of the bug.&lt;br /&gt;
*Repetition of the same bug reduced: With TDD once a bug is found, it's put under test. So every time you run the whole test in the system, the tests associated with the bug are run and make sure the bugs are not generated again.&lt;br /&gt;
&lt;br /&gt;
=Shortcomings Of TDD=&lt;br /&gt;
&lt;br /&gt;
TDD has a few shortcomings:&lt;br /&gt;
&lt;br /&gt;
*The actual database or external file is never tested directly by TDD (only production code can test it)&lt;br /&gt;
*If not used carefully, it can add to the total project costs and complexity of the project&lt;br /&gt;
*TDD is unable to test UI.&lt;br /&gt;
*TDD is highly reliant on Refactoring and Programmer Skills.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
Danielle&lt;br /&gt;
=References=&lt;br /&gt;
*[http://catalog.lib.ncsu.edu/record/NCSU1601963 Beck, K. (2002). Test-driven development by example. Addison-Wesley.]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Test_driven_development (n.d.). Test-driven development. website: http://en.wikipedia.org/wiki/Test_driven_development]&lt;br /&gt;
*[http://c2.com/cgi/wiki?TestDrivenDevelopment (2012, January 11). Test driven development. website: http://c2.com/cgi/wiki?TestDrivenDevelopment]&lt;br /&gt;
*[http://www.agiledata.org/essays/tdd.html Ambler, S. W. (2002). Introduction to test driven development (tdd). Retrieved from Agile Data website: http://www.agiledata.org/essays/tdd.html]&lt;br /&gt;
*[http://www.methodsandtools.com/archive/archive.php?id=20. Methods and Tools Archives]&lt;br /&gt;
*[http://www.martinfowler.com/bliki/TestDrivenDevelopment.html www.martinfowler.com/bliki/TestDrivenDevelopment]&lt;br /&gt;
*[http://www.codeproject.com/Articles/47747/Test-Driven-Development-TDD-Step-by-Step-Part-1-In TDD Step by Step Code Project]&lt;br /&gt;
*[http://integralpath.blogs.com/thinkingoutloud/2005/09/principles_of_t.html Principles of Testing]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=68182</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w11 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=68182"/>
		<updated>2012-10-25T16:57:13Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Benefits Of TDD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Introduction=&lt;br /&gt;
Test driven development (TDD) is a process that tries to create the minimal amount of code to meet customer's expectations. The idea is to test first, code second, then improve (or refactor) last. This process forces the software developers to focus on customer specifications and validation first. Since at each step of the way the programmer proves to himself that the code meets specifications, TDD gives the programmer confidence. The rest of this chapter gives the motivation for TDD, shows the steps for TDD, outlines the principles of TDD, provides examples using TDD, and compares the pros and cons of TDD.&lt;br /&gt;
&lt;br /&gt;
=Motivation for TDD=&lt;br /&gt;
&lt;br /&gt;
There are two main motivations for TDD.&lt;br /&gt;
&lt;br /&gt;
[[File:TimevsCostDev.png|350px|Thumb:Figure 1: Traditional &amp;quot;Cost of Change&amp;quot; curve with the waterfall model superimposed]]&lt;br /&gt;
&lt;br /&gt;
*Testing is the one activity that improves the quality of code. In various design scenarios, like waterfall model, testing occurs towards the end of the project development activity. As shown in the figure 1, introducing testing as a latter phase increases the cost incurred for implementing the changes. From this we infer that there is a high chance of reducing the costs by moving the Test phase to the initial part.&lt;br /&gt;
*The client can also be well informed about the design and can suggest changes which can be incorporated well in advance. This approach also known as TDD helps achieve flexibility to achieve the client’s ever-changing requirements&lt;br /&gt;
&lt;br /&gt;
=Principles=&lt;br /&gt;
&lt;br /&gt;
TDD follows several principles:&lt;br /&gt;
&lt;br /&gt;
*Tests serve as examples of how to use a class or method.  Once used to having tests that show how things work (and that they work), developers start inquiring if a test was already there for the piece of code to be developed&lt;br /&gt;
*Developer tests are distinctly different from QA (Quality Analysis) tests and should be kept separate.  QA tests target features and treat the system as a black box.  Unit tests created by the developer operate at a lower level and test different things.&lt;br /&gt;
*Name the tests carefully.  For Example, name test packages like the package being tested with a suffix.  For example, the &amp;quot;DataAccess&amp;quot; project/package is tested by &amp;quot;DataAccess.Test&amp;quot;. Also,  name test classes the same as the class under test with the suffix &amp;quot;Test&amp;quot;.  For example, the class &amp;quot;PrintManager&amp;quot; is tested by the test class &amp;quot;PrintManagerTest&amp;quot;.  This convention makes it easy to find the related class and keeps the class name a noun. You should also name test methods the same as the method being tested with the prefix &amp;quot;Test&amp;quot;.  For example, the method &amp;quot;PrintProductOrder()&amp;quot; is tested by the method &amp;quot;TestPrintProductOrder()&amp;quot;.  This convention keeps the method name a verb that reads as an english phrase.  &lt;br /&gt;
*Write each test before writing the method under test. It encourages the developer to think as a user of the target method before thinking about implementation, which usually results in a cleaner, easier-to-use interface.&lt;br /&gt;
*Follow the &amp;quot;3-As&amp;quot; pattern for test methods: Arrange, Act, Assert. Specifically, use separate code paragraphs (groups of lines of code separated by a blank line) for each of the As.  Arrange is variable declaration and initialization.  Act is invoking the code under test.  Assert is using the Assert.* methods to verify that expectations were met. &lt;br /&gt;
*When writing application code, only write enough code to make a test work. This technique prevents gold-plating and ensures that you always have a test for the code you write. &lt;br /&gt;
*When you find you need to refractor working code, refractor and re-test prior to writing new code.  This technique ensures your refractoring is correct prior to adding new functionality and applies to creating new methods, introducing inheritance, everything.&lt;br /&gt;
&lt;br /&gt;
=Steps=&lt;br /&gt;
&lt;br /&gt;
[[Image:PureFab.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Follow these steps:&lt;br /&gt;
*Understand the requirements of the story, work item, or feature that you are working on.&lt;br /&gt;
*Red:Create a test and make it fail.&lt;br /&gt;
Imagine how the new code should be called and write the test as if the code already existed.&lt;br /&gt;
Create the new production code stub. Write just enough code so that it compiles.&lt;br /&gt;
Run the test. It should fail. This is a calibration measure to ensure that your test is calling the correct code and that the code is not working by accident. This is a meaningful failure, and you expect it to fail.&lt;br /&gt;
*Green: Make the test pass by any means necessary.&lt;br /&gt;
Write the production code to make the test pass. Keep it simple.&lt;br /&gt;
Some advocate the hard-coding of the expected return value first to verify that the test correctly detects success. This varies from practitioner to practitioner.If you've written the code so that the test passes as intended, you are finished. You do not have to write more code speculatively. If new functionality is still needed, then another test is needed. Make this one test pass and continue.&lt;br /&gt;
When the test passes, you might want to run all tests up to this point to build confidence that everything else is still working.&lt;br /&gt;
*Refractor: Change the code to remove duplication in your project and to improve the design while ensuring that all tests still pass.&lt;br /&gt;
Remove duplication caused by the addition of the new functionality.&lt;br /&gt;
Make design changes to improve the overall solution.&lt;br /&gt;
After each refactoring, rerun all the tests to ensure that they all still pass.&lt;br /&gt;
*Repeat the cycle. Each cycle should be very short, and a typical hour should contain many Red/Green/ Refractor cycles.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
&lt;br /&gt;
==Homework Grades Program==&lt;br /&gt;
&lt;br /&gt;
===Setup===&lt;br /&gt;
As a simple example, we are creating a program that keeps track of our homework grades. We envision that we would be able to get the average of these homework grades. Step one: &amp;lt;b&amp;gt; write a test &amp;lt;/b&amp;gt;. Let's test an average function&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We will get multiple errors - this test won't even compile (but, that's ok for now). Let's take a look at what will generate error messages:&lt;br /&gt;
&lt;br /&gt;
* class &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; constructor not declared&lt;br /&gt;
* field &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* method &amp;lt;code&amp;gt;average&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
&lt;br /&gt;
Now, we fix the first error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Second error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Homework(void) {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Third error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int * grades;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fourth error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int average(int * grades) {&lt;br /&gt;
  return 0; // default return value&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, the test compiles! The code now looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
&lt;br /&gt;
    return 0; // default return value&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
Now, we run the test, and the familar red bar of failure greets us (remember the mantra red-green-refactor). The assert fails. The average function needs to actually average something (not just return 0). As we think about averaging the grades, we realize we need to know how many grades are in the int array &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt;. So, we add to the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
  int numGrades;                         // new&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
 &lt;br /&gt;
   int avg = 0;                         // new&lt;br /&gt;
 &lt;br /&gt;
   for(int i = 0; i &amp;lt; numGrades; i++) { // new&lt;br /&gt;
     avg += grades[i];                  // new&lt;br /&gt;
   }                                    // new&lt;br /&gt;
 &lt;br /&gt;
   return avg/numGrades;                // new&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Of course, we must remember to change the test to:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  myHomework.numGrades = 2;&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
Success! We have a green bar when we run it. &lt;br /&gt;
&lt;br /&gt;
===Refactor===&lt;br /&gt;
The last step is refactoring. Perhaps we don't want a grade to be an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;? Should it be an &amp;lt;code&amp;gt;unsigned int&amp;lt;/code&amp;gt;? For this simple example, there isn't much refactoring to do, but in a larger example there may be multiple areas for improvement.&lt;br /&gt;
&lt;br /&gt;
==Refactoring Example==&lt;br /&gt;
The following example is take from &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck.&lt;br /&gt;
&lt;br /&gt;
Using the TDD process the author created an object with the following structure:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dollar {&lt;br /&gt;
 &lt;br /&gt;
  Dollar(int amount) {&lt;br /&gt;
     this.amount = amount;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  void times(int mulitplier) {&lt;br /&gt;
    amount *= multiplier;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
What's wrong with the code above? Look at the following test:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  &lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  five.times(2);&lt;br /&gt;
  assertEquals(10, five.amount);&lt;br /&gt;
  five.times(3);&lt;br /&gt;
  assertEquals(15, five.amount);&lt;br /&gt;
&lt;br /&gt;
}  &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Whenever we perform an operation on a &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; the value of the &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; changes. In the test above &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; isn't 5 after we multiply it by 2, and thus the name &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; doesn't make sense anymore. How do we change this? &lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
&lt;br /&gt;
First, we change the &amp;lt;b&amp;gt;test&amp;lt;/b&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  Dollar product = five.times(2);&lt;br /&gt;
  assertEquals(10, product.amount);&lt;br /&gt;
  product = five.times(3);&lt;br /&gt;
  assertEquals(15, product.amount);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new test won't compile until we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  amount *= multiplier;&lt;br /&gt;
  return null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now the test compiles, but fails. Once again, we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  return new Dollar(amount * multiplier);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
&lt;br /&gt;
The test succeeds. So we see that even when we are refactoring we change the test first, then the code. This way we know our refactoring is an improvement.&lt;br /&gt;
&lt;br /&gt;
==More Examples==&lt;br /&gt;
See &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck for more examples.&lt;br /&gt;
&lt;br /&gt;
=Characteristics Of A Good Unit Test=&lt;br /&gt;
A good unit test has the following characteristics.&lt;br /&gt;
*It is important that the test executes fast. If the tests are slow, they will not be run often.&lt;br /&gt;
*Environmental dependencies such as databases, file systems, networks, queues, and so on which will slow down the tests are either separated or simulated. Tests that exercise these will not run fast, and a failure does not give meaningful feedback about what the problem actually is.&lt;br /&gt;
*The scope of testing is very limited. If the test fails, it's obvious where to look for the problem. It's important to only test one aspect in a single test.&lt;br /&gt;
*The test should run and pass in isolation (on any machine). If the tests require special environmental setup or fail unexpectedly, then they are not good unit tests.&lt;br /&gt;
*Such a test often uses stubs and mock objects. If the code being tested typically calls out to a database or file system, these dependencies must be simulated, or mocked. These dependencies will ordinarily be abstracted away by using interfaces.&lt;br /&gt;
*The intention of testing is clearly revealed. Another developer can look at the test and understand what is expected of the production code.&lt;br /&gt;
&lt;br /&gt;
=Benefits Of TDD=&lt;br /&gt;
&lt;br /&gt;
Using TDD has many benefits.&lt;br /&gt;
&lt;br /&gt;
*Automated testing: Automated system makes the testing much more easier and faster. Manual testing is slower and needs human interaction which is error-prone. Automated testing makes sure any particular test is not missing every time we test the system, whereas humans may leave a test out mistakenly during testing process.&lt;br /&gt;
*Better to test New/Modified Functionality: With manual testing whenever you add new functionality or modify existing functionality, QA personal needs to test all systems that may be affected due to the modification which may be time-consuming. This may also leave a hidden bug in the system after modification. With TDD whenever a new functionality is added or existing functionality is modified, the whole set of tests in the system is run to make sure existing tests are passed. This makes sure that existing functionality is not broken.&lt;br /&gt;
*Developer’s confidence: With TDD, developers are more safe to change the system as any inappropriate changes will make some tests to fail. With non-TDD system developers needs to take more care to change existing system as the new change may fail other functionality. But with TDD developers can do so easily as after modification if developer runs the test he/she will find immediately that the change has failed some other tests (i.e. some other part of the system).&lt;br /&gt;
*Manual testing stage is shortened: In non-TDD development, as soon as developers prepare a build, QA personal starts testing. This manual testing takes a reasonable amount of time and increases the time to deliver the product from the build time. With TDD, a major part of the system is tested during development and needs lesser QA involvement in the time between build and final delivery of the product.&lt;br /&gt;
*Alternative Documentation: Unit tests are kind of documentation to system. Each unit test tells about an individual requirement to the module or system. For example, the following test ensures that only a logged in user with proper balance can buy an item when the item exists in stock. This test reflects a user aspect scenario of the system.&lt;br /&gt;
&lt;br /&gt;
     public void CheckUserCanNotPurchaseItemWithoutBalance(){  &lt;br /&gt;
     LoginToTheSystem();       &lt;br /&gt;
     SelectAnItemToBuy();       &lt;br /&gt;
     MakeSureItemExsitsInStock();       &lt;br /&gt;
     MakeSureUserHasBalanceToBuy();      &lt;br /&gt;
     RunTheTransaction(); &lt;br /&gt;
  }			&lt;br /&gt;
*Better way to fix bugs: In TDD approach when QA finds a bug, developer first writes a test that generates the bug (that is the test will fail due to this bug). Then developer modifies code to make sure that the test is passed (i.e., the bug is fixed). This approach makes sure that next time the bug will not appear in the system as a test is written in the system to take care of the bug.&lt;br /&gt;
*Repetition of the same bug reduced: With TDD once a bug is found, it's put under test. So every time you run the whole test in the system, the tests associated with the bug are run and make sure the bugs are not generated again.&lt;br /&gt;
&lt;br /&gt;
=Shortcomings Of TDD=&lt;br /&gt;
*The actual database or external file is never tested directly by TDD (only production code can test it)&lt;br /&gt;
*If not used carefully, it can add to the total project costs and complexity of the project&lt;br /&gt;
*TDD is unable to test UI.&lt;br /&gt;
*TDD is highly reliant on Refactoring and Programmer Skills.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
Danielle&lt;br /&gt;
=References=&lt;br /&gt;
*[http://catalog.lib.ncsu.edu/record/NCSU1601963 Beck, K. (2002). Test-driven development by example. Addison-Wesley.]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Test_driven_development (n.d.). Test-driven development. website: http://en.wikipedia.org/wiki/Test_driven_development]&lt;br /&gt;
*[http://c2.com/cgi/wiki?TestDrivenDevelopment (2012, January 11). Test driven development. website: http://c2.com/cgi/wiki?TestDrivenDevelopment]&lt;br /&gt;
*[http://www.agiledata.org/essays/tdd.html Ambler, S. W. (2002). Introduction to test driven development (tdd). Retrieved from Agile Data website: http://www.agiledata.org/essays/tdd.html]&lt;br /&gt;
*[http://www.methodsandtools.com/archive/archive.php?id=20. Methods and Tools Archives]&lt;br /&gt;
*[http://www.martinfowler.com/bliki/TestDrivenDevelopment.html www.martinfowler.com/bliki/TestDrivenDevelopment]&lt;br /&gt;
*[http://www.codeproject.com/Articles/47747/Test-Driven-Development-TDD-Step-by-Step-Part-1-In TDD Step by Step Code Project]&lt;br /&gt;
*[http://integralpath.blogs.com/thinkingoutloud/2005/09/principles_of_t.html Principles of Testing]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=68181</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w11 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=68181"/>
		<updated>2012-10-25T16:56:33Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Principles */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Introduction=&lt;br /&gt;
Test driven development (TDD) is a process that tries to create the minimal amount of code to meet customer's expectations. The idea is to test first, code second, then improve (or refactor) last. This process forces the software developers to focus on customer specifications and validation first. Since at each step of the way the programmer proves to himself that the code meets specifications, TDD gives the programmer confidence. The rest of this chapter gives the motivation for TDD, shows the steps for TDD, outlines the principles of TDD, provides examples using TDD, and compares the pros and cons of TDD.&lt;br /&gt;
&lt;br /&gt;
=Motivation for TDD=&lt;br /&gt;
&lt;br /&gt;
There are two main motivations for TDD.&lt;br /&gt;
&lt;br /&gt;
[[File:TimevsCostDev.png|350px|Thumb:Figure 1: Traditional &amp;quot;Cost of Change&amp;quot; curve with the waterfall model superimposed]]&lt;br /&gt;
&lt;br /&gt;
*Testing is the one activity that improves the quality of code. In various design scenarios, like waterfall model, testing occurs towards the end of the project development activity. As shown in the figure 1, introducing testing as a latter phase increases the cost incurred for implementing the changes. From this we infer that there is a high chance of reducing the costs by moving the Test phase to the initial part.&lt;br /&gt;
*The client can also be well informed about the design and can suggest changes which can be incorporated well in advance. This approach also known as TDD helps achieve flexibility to achieve the client’s ever-changing requirements&lt;br /&gt;
&lt;br /&gt;
=Principles=&lt;br /&gt;
&lt;br /&gt;
TDD follows several principles:&lt;br /&gt;
&lt;br /&gt;
*Tests serve as examples of how to use a class or method.  Once used to having tests that show how things work (and that they work), developers start inquiring if a test was already there for the piece of code to be developed&lt;br /&gt;
*Developer tests are distinctly different from QA (Quality Analysis) tests and should be kept separate.  QA tests target features and treat the system as a black box.  Unit tests created by the developer operate at a lower level and test different things.&lt;br /&gt;
*Name the tests carefully.  For Example, name test packages like the package being tested with a suffix.  For example, the &amp;quot;DataAccess&amp;quot; project/package is tested by &amp;quot;DataAccess.Test&amp;quot;. Also,  name test classes the same as the class under test with the suffix &amp;quot;Test&amp;quot;.  For example, the class &amp;quot;PrintManager&amp;quot; is tested by the test class &amp;quot;PrintManagerTest&amp;quot;.  This convention makes it easy to find the related class and keeps the class name a noun. You should also name test methods the same as the method being tested with the prefix &amp;quot;Test&amp;quot;.  For example, the method &amp;quot;PrintProductOrder()&amp;quot; is tested by the method &amp;quot;TestPrintProductOrder()&amp;quot;.  This convention keeps the method name a verb that reads as an english phrase.  &lt;br /&gt;
*Write each test before writing the method under test. It encourages the developer to think as a user of the target method before thinking about implementation, which usually results in a cleaner, easier-to-use interface.&lt;br /&gt;
*Follow the &amp;quot;3-As&amp;quot; pattern for test methods: Arrange, Act, Assert. Specifically, use separate code paragraphs (groups of lines of code separated by a blank line) for each of the As.  Arrange is variable declaration and initialization.  Act is invoking the code under test.  Assert is using the Assert.* methods to verify that expectations were met. &lt;br /&gt;
*When writing application code, only write enough code to make a test work. This technique prevents gold-plating and ensures that you always have a test for the code you write. &lt;br /&gt;
*When you find you need to refractor working code, refractor and re-test prior to writing new code.  This technique ensures your refractoring is correct prior to adding new functionality and applies to creating new methods, introducing inheritance, everything.&lt;br /&gt;
&lt;br /&gt;
=Steps=&lt;br /&gt;
&lt;br /&gt;
[[Image:PureFab.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Follow these steps:&lt;br /&gt;
*Understand the requirements of the story, work item, or feature that you are working on.&lt;br /&gt;
*Red:Create a test and make it fail.&lt;br /&gt;
Imagine how the new code should be called and write the test as if the code already existed.&lt;br /&gt;
Create the new production code stub. Write just enough code so that it compiles.&lt;br /&gt;
Run the test. It should fail. This is a calibration measure to ensure that your test is calling the correct code and that the code is not working by accident. This is a meaningful failure, and you expect it to fail.&lt;br /&gt;
*Green: Make the test pass by any means necessary.&lt;br /&gt;
Write the production code to make the test pass. Keep it simple.&lt;br /&gt;
Some advocate the hard-coding of the expected return value first to verify that the test correctly detects success. This varies from practitioner to practitioner.If you've written the code so that the test passes as intended, you are finished. You do not have to write more code speculatively. If new functionality is still needed, then another test is needed. Make this one test pass and continue.&lt;br /&gt;
When the test passes, you might want to run all tests up to this point to build confidence that everything else is still working.&lt;br /&gt;
*Refractor: Change the code to remove duplication in your project and to improve the design while ensuring that all tests still pass.&lt;br /&gt;
Remove duplication caused by the addition of the new functionality.&lt;br /&gt;
Make design changes to improve the overall solution.&lt;br /&gt;
After each refactoring, rerun all the tests to ensure that they all still pass.&lt;br /&gt;
*Repeat the cycle. Each cycle should be very short, and a typical hour should contain many Red/Green/ Refractor cycles.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
&lt;br /&gt;
==Homework Grades Program==&lt;br /&gt;
&lt;br /&gt;
===Setup===&lt;br /&gt;
As a simple example, we are creating a program that keeps track of our homework grades. We envision that we would be able to get the average of these homework grades. Step one: &amp;lt;b&amp;gt; write a test &amp;lt;/b&amp;gt;. Let's test an average function&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We will get multiple errors - this test won't even compile (but, that's ok for now). Let's take a look at what will generate error messages:&lt;br /&gt;
&lt;br /&gt;
* class &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; constructor not declared&lt;br /&gt;
* field &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* method &amp;lt;code&amp;gt;average&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
&lt;br /&gt;
Now, we fix the first error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Second error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Homework(void) {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Third error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int * grades;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fourth error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int average(int * grades) {&lt;br /&gt;
  return 0; // default return value&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, the test compiles! The code now looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
&lt;br /&gt;
    return 0; // default return value&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
Now, we run the test, and the familar red bar of failure greets us (remember the mantra red-green-refactor). The assert fails. The average function needs to actually average something (not just return 0). As we think about averaging the grades, we realize we need to know how many grades are in the int array &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt;. So, we add to the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
  int numGrades;                         // new&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
 &lt;br /&gt;
   int avg = 0;                         // new&lt;br /&gt;
 &lt;br /&gt;
   for(int i = 0; i &amp;lt; numGrades; i++) { // new&lt;br /&gt;
     avg += grades[i];                  // new&lt;br /&gt;
   }                                    // new&lt;br /&gt;
 &lt;br /&gt;
   return avg/numGrades;                // new&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Of course, we must remember to change the test to:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  myHomework.numGrades = 2;&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
Success! We have a green bar when we run it. &lt;br /&gt;
&lt;br /&gt;
===Refactor===&lt;br /&gt;
The last step is refactoring. Perhaps we don't want a grade to be an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;? Should it be an &amp;lt;code&amp;gt;unsigned int&amp;lt;/code&amp;gt;? For this simple example, there isn't much refactoring to do, but in a larger example there may be multiple areas for improvement.&lt;br /&gt;
&lt;br /&gt;
==Refactoring Example==&lt;br /&gt;
The following example is take from &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck.&lt;br /&gt;
&lt;br /&gt;
Using the TDD process the author created an object with the following structure:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dollar {&lt;br /&gt;
 &lt;br /&gt;
  Dollar(int amount) {&lt;br /&gt;
     this.amount = amount;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  void times(int mulitplier) {&lt;br /&gt;
    amount *= multiplier;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
What's wrong with the code above? Look at the following test:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  &lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  five.times(2);&lt;br /&gt;
  assertEquals(10, five.amount);&lt;br /&gt;
  five.times(3);&lt;br /&gt;
  assertEquals(15, five.amount);&lt;br /&gt;
&lt;br /&gt;
}  &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Whenever we perform an operation on a &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; the value of the &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; changes. In the test above &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; isn't 5 after we multiply it by 2, and thus the name &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; doesn't make sense anymore. How do we change this? &lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
&lt;br /&gt;
First, we change the &amp;lt;b&amp;gt;test&amp;lt;/b&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  Dollar product = five.times(2);&lt;br /&gt;
  assertEquals(10, product.amount);&lt;br /&gt;
  product = five.times(3);&lt;br /&gt;
  assertEquals(15, product.amount);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new test won't compile until we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  amount *= multiplier;&lt;br /&gt;
  return null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now the test compiles, but fails. Once again, we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  return new Dollar(amount * multiplier);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
&lt;br /&gt;
The test succeeds. So we see that even when we are refactoring we change the test first, then the code. This way we know our refactoring is an improvement.&lt;br /&gt;
&lt;br /&gt;
==More Examples==&lt;br /&gt;
See &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck for more examples.&lt;br /&gt;
&lt;br /&gt;
=Characteristics Of A Good Unit Test=&lt;br /&gt;
A good unit test has the following characteristics.&lt;br /&gt;
*It is important that the test executes fast. If the tests are slow, they will not be run often.&lt;br /&gt;
*Environmental dependencies such as databases, file systems, networks, queues, and so on which will slow down the tests are either separated or simulated. Tests that exercise these will not run fast, and a failure does not give meaningful feedback about what the problem actually is.&lt;br /&gt;
*The scope of testing is very limited. If the test fails, it's obvious where to look for the problem. It's important to only test one aspect in a single test.&lt;br /&gt;
*The test should run and pass in isolation (on any machine). If the tests require special environmental setup or fail unexpectedly, then they are not good unit tests.&lt;br /&gt;
*Such a test often uses stubs and mock objects. If the code being tested typically calls out to a database or file system, these dependencies must be simulated, or mocked. These dependencies will ordinarily be abstracted away by using interfaces.&lt;br /&gt;
*The intention of testing is clearly revealed. Another developer can look at the test and understand what is expected of the production code.&lt;br /&gt;
&lt;br /&gt;
=Benefits Of TDD=&lt;br /&gt;
*Automated testing: Automated system makes the testing much more easier and faster. Manual testing is slower and needs human interaction which is error-prone. Automated testing makes sure any particular test is not missing every time we test the system, whereas humans may leave a test out mistakenly during testing process.&lt;br /&gt;
*Better to test New/Modified Functionality: With manual testing whenever you add new functionality or modify existing functionality, QA personal needs to test all systems that may be affected due to the modification which may be time-consuming. This may also leave a hidden bug in the system after modification. With TDD whenever a new functionality is added or existing functionality is modified, the whole set of tests in the system is run to make sure existing tests are passed. This makes sure that existing functionality is not broken.&lt;br /&gt;
*Developer’s confidence: With TDD, developers are more safe to change the system as any inappropriate changes will make some tests to fail. With non-TDD system developers needs to take more care to change existing system as the new change may fail other functionality. But with TDD developers can do so easily as after modification if developer runs the test he/she will find immediately that the change has failed some other tests (i.e. some other part of the system).&lt;br /&gt;
*Manual testing stage is shortened: In non-TDD development, as soon as developers prepare a build, QA personal starts testing. This manual testing takes a reasonable amount of time and increases the time to deliver the product from the build time. With TDD, a major part of the system is tested during development and needs lesser QA involvement in the time between build and final delivery of the product.&lt;br /&gt;
*Alternative Documentation: Unit tests are kind of documentation to system. Each unit test tells about an individual requirement to the module or system. For example, the following test ensures that only a logged in user with proper balance can buy an item when the item exists in stock. This test reflects a user aspect scenario of the system.&lt;br /&gt;
&lt;br /&gt;
     public void CheckUserCanNotPurchaseItemWithoutBalance(){  &lt;br /&gt;
     LoginToTheSystem();       &lt;br /&gt;
     SelectAnItemToBuy();       &lt;br /&gt;
     MakeSureItemExsitsInStock();       &lt;br /&gt;
     MakeSureUserHasBalanceToBuy();      &lt;br /&gt;
     RunTheTransaction(); &lt;br /&gt;
  }			&lt;br /&gt;
*Better way to fix bugs: In TDD approach when QA finds a bug, developer first writes a test that generates the bug (that is the test will fail due to this bug). Then developer modifies code to make sure that the test is passed (i.e., the bug is fixed). This approach makes sure that next time the bug will not appear in the system as a test is written in the system to take care of the bug.&lt;br /&gt;
*Repetition of the same bug reduced: With TDD once a bug is found, it's put under test. So every time you run the whole test in the system, the tests associated with the bug are run and make sure the bugs are not generated again.&lt;br /&gt;
&lt;br /&gt;
=Shortcomings Of TDD=&lt;br /&gt;
*The actual database or external file is never tested directly by TDD (only production code can test it)&lt;br /&gt;
*If not used carefully, it can add to the total project costs and complexity of the project&lt;br /&gt;
*TDD is unable to test UI.&lt;br /&gt;
*TDD is highly reliant on Refactoring and Programmer Skills.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
Danielle&lt;br /&gt;
=References=&lt;br /&gt;
*[http://catalog.lib.ncsu.edu/record/NCSU1601963 Beck, K. (2002). Test-driven development by example. Addison-Wesley.]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Test_driven_development (n.d.). Test-driven development. website: http://en.wikipedia.org/wiki/Test_driven_development]&lt;br /&gt;
*[http://c2.com/cgi/wiki?TestDrivenDevelopment (2012, January 11). Test driven development. website: http://c2.com/cgi/wiki?TestDrivenDevelopment]&lt;br /&gt;
*[http://www.agiledata.org/essays/tdd.html Ambler, S. W. (2002). Introduction to test driven development (tdd). Retrieved from Agile Data website: http://www.agiledata.org/essays/tdd.html]&lt;br /&gt;
*[http://www.methodsandtools.com/archive/archive.php?id=20. Methods and Tools Archives]&lt;br /&gt;
*[http://www.martinfowler.com/bliki/TestDrivenDevelopment.html www.martinfowler.com/bliki/TestDrivenDevelopment]&lt;br /&gt;
*[http://www.codeproject.com/Articles/47747/Test-Driven-Development-TDD-Step-by-Step-Part-1-In TDD Step by Step Code Project]&lt;br /&gt;
*[http://integralpath.blogs.com/thinkingoutloud/2005/09/principles_of_t.html Principles of Testing]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=68180</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w11 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=68180"/>
		<updated>2012-10-25T16:56:08Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Motivation for TDD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Introduction=&lt;br /&gt;
Test driven development (TDD) is a process that tries to create the minimal amount of code to meet customer's expectations. The idea is to test first, code second, then improve (or refactor) last. This process forces the software developers to focus on customer specifications and validation first. Since at each step of the way the programmer proves to himself that the code meets specifications, TDD gives the programmer confidence. The rest of this chapter gives the motivation for TDD, shows the steps for TDD, outlines the principles of TDD, provides examples using TDD, and compares the pros and cons of TDD.&lt;br /&gt;
&lt;br /&gt;
=Motivation for TDD=&lt;br /&gt;
&lt;br /&gt;
There are two main motivations for TDD.&lt;br /&gt;
&lt;br /&gt;
[[File:TimevsCostDev.png|350px|Thumb:Figure 1: Traditional &amp;quot;Cost of Change&amp;quot; curve with the waterfall model superimposed]]&lt;br /&gt;
&lt;br /&gt;
*Testing is the one activity that improves the quality of code. In various design scenarios, like waterfall model, testing occurs towards the end of the project development activity. As shown in the figure 1, introducing testing as a latter phase increases the cost incurred for implementing the changes. From this we infer that there is a high chance of reducing the costs by moving the Test phase to the initial part.&lt;br /&gt;
*The client can also be well informed about the design and can suggest changes which can be incorporated well in advance. This approach also known as TDD helps achieve flexibility to achieve the client’s ever-changing requirements&lt;br /&gt;
&lt;br /&gt;
=Principles=&lt;br /&gt;
*Tests serve as examples of how to use a class or method.  Once used to having tests that show how things work (and that they work), developers start inquiring if a test was already there for the piece of code to be developed&lt;br /&gt;
*Developer tests are distinctly different from QA (Quality Analysis) tests and should be kept separate.  QA tests target features and treat the system as a black box.  Unit tests created by the developer operate at a lower level and test different things.&lt;br /&gt;
*Name the tests carefully.  For Example, name test packages like the package being tested with a suffix.  For example, the &amp;quot;DataAccess&amp;quot; project/package is tested by &amp;quot;DataAccess.Test&amp;quot;. Also,  name test classes the same as the class under test with the suffix &amp;quot;Test&amp;quot;.  For example, the class &amp;quot;PrintManager&amp;quot; is tested by the test class &amp;quot;PrintManagerTest&amp;quot;.  This convention makes it easy to find the related class and keeps the class name a noun. You should also name test methods the same as the method being tested with the prefix &amp;quot;Test&amp;quot;.  For example, the method &amp;quot;PrintProductOrder()&amp;quot; is tested by the method &amp;quot;TestPrintProductOrder()&amp;quot;.  This convention keeps the method name a verb that reads as an english phrase.  &lt;br /&gt;
*Write each test before writing the method under test. It encourages the developer to think as a user of the target method before thinking about implementation, which usually results in a cleaner, easier-to-use interface.&lt;br /&gt;
*Follow the &amp;quot;3-As&amp;quot; pattern for test methods: Arrange, Act, Assert. Specifically, use separate code paragraphs (groups of lines of code separated by a blank line) for each of the As.  Arrange is variable declaration and initialization.  Act is invoking the code under test.  Assert is using the Assert.* methods to verify that expectations were met. &lt;br /&gt;
*When writing application code, only write enough code to make a test work. This technique prevents gold-plating and ensures that you always have a test for the code you write. &lt;br /&gt;
*When you find you need to refractor working code, refractor and re-test prior to writing new code.  This technique ensures your refractoring is correct prior to adding new functionality and applies to creating new methods, introducing inheritance, everything.&lt;br /&gt;
=Steps=&lt;br /&gt;
&lt;br /&gt;
[[Image:PureFab.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Follow these steps:&lt;br /&gt;
*Understand the requirements of the story, work item, or feature that you are working on.&lt;br /&gt;
*Red:Create a test and make it fail.&lt;br /&gt;
Imagine how the new code should be called and write the test as if the code already existed.&lt;br /&gt;
Create the new production code stub. Write just enough code so that it compiles.&lt;br /&gt;
Run the test. It should fail. This is a calibration measure to ensure that your test is calling the correct code and that the code is not working by accident. This is a meaningful failure, and you expect it to fail.&lt;br /&gt;
*Green: Make the test pass by any means necessary.&lt;br /&gt;
Write the production code to make the test pass. Keep it simple.&lt;br /&gt;
Some advocate the hard-coding of the expected return value first to verify that the test correctly detects success. This varies from practitioner to practitioner.If you've written the code so that the test passes as intended, you are finished. You do not have to write more code speculatively. If new functionality is still needed, then another test is needed. Make this one test pass and continue.&lt;br /&gt;
When the test passes, you might want to run all tests up to this point to build confidence that everything else is still working.&lt;br /&gt;
*Refractor: Change the code to remove duplication in your project and to improve the design while ensuring that all tests still pass.&lt;br /&gt;
Remove duplication caused by the addition of the new functionality.&lt;br /&gt;
Make design changes to improve the overall solution.&lt;br /&gt;
After each refactoring, rerun all the tests to ensure that they all still pass.&lt;br /&gt;
*Repeat the cycle. Each cycle should be very short, and a typical hour should contain many Red/Green/ Refractor cycles.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
&lt;br /&gt;
==Homework Grades Program==&lt;br /&gt;
&lt;br /&gt;
===Setup===&lt;br /&gt;
As a simple example, we are creating a program that keeps track of our homework grades. We envision that we would be able to get the average of these homework grades. Step one: &amp;lt;b&amp;gt; write a test &amp;lt;/b&amp;gt;. Let's test an average function&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We will get multiple errors - this test won't even compile (but, that's ok for now). Let's take a look at what will generate error messages:&lt;br /&gt;
&lt;br /&gt;
* class &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; constructor not declared&lt;br /&gt;
* field &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* method &amp;lt;code&amp;gt;average&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
&lt;br /&gt;
Now, we fix the first error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Second error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Homework(void) {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Third error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int * grades;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fourth error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int average(int * grades) {&lt;br /&gt;
  return 0; // default return value&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, the test compiles! The code now looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
&lt;br /&gt;
    return 0; // default return value&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
Now, we run the test, and the familar red bar of failure greets us (remember the mantra red-green-refactor). The assert fails. The average function needs to actually average something (not just return 0). As we think about averaging the grades, we realize we need to know how many grades are in the int array &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt;. So, we add to the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
  int numGrades;                         // new&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
 &lt;br /&gt;
   int avg = 0;                         // new&lt;br /&gt;
 &lt;br /&gt;
   for(int i = 0; i &amp;lt; numGrades; i++) { // new&lt;br /&gt;
     avg += grades[i];                  // new&lt;br /&gt;
   }                                    // new&lt;br /&gt;
 &lt;br /&gt;
   return avg/numGrades;                // new&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Of course, we must remember to change the test to:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  myHomework.numGrades = 2;&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
Success! We have a green bar when we run it. &lt;br /&gt;
&lt;br /&gt;
===Refactor===&lt;br /&gt;
The last step is refactoring. Perhaps we don't want a grade to be an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;? Should it be an &amp;lt;code&amp;gt;unsigned int&amp;lt;/code&amp;gt;? For this simple example, there isn't much refactoring to do, but in a larger example there may be multiple areas for improvement.&lt;br /&gt;
&lt;br /&gt;
==Refactoring Example==&lt;br /&gt;
The following example is take from &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck.&lt;br /&gt;
&lt;br /&gt;
Using the TDD process the author created an object with the following structure:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dollar {&lt;br /&gt;
 &lt;br /&gt;
  Dollar(int amount) {&lt;br /&gt;
     this.amount = amount;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  void times(int mulitplier) {&lt;br /&gt;
    amount *= multiplier;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
What's wrong with the code above? Look at the following test:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  &lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  five.times(2);&lt;br /&gt;
  assertEquals(10, five.amount);&lt;br /&gt;
  five.times(3);&lt;br /&gt;
  assertEquals(15, five.amount);&lt;br /&gt;
&lt;br /&gt;
}  &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Whenever we perform an operation on a &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; the value of the &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; changes. In the test above &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; isn't 5 after we multiply it by 2, and thus the name &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; doesn't make sense anymore. How do we change this? &lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
&lt;br /&gt;
First, we change the &amp;lt;b&amp;gt;test&amp;lt;/b&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  Dollar product = five.times(2);&lt;br /&gt;
  assertEquals(10, product.amount);&lt;br /&gt;
  product = five.times(3);&lt;br /&gt;
  assertEquals(15, product.amount);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new test won't compile until we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  amount *= multiplier;&lt;br /&gt;
  return null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now the test compiles, but fails. Once again, we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  return new Dollar(amount * multiplier);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
&lt;br /&gt;
The test succeeds. So we see that even when we are refactoring we change the test first, then the code. This way we know our refactoring is an improvement.&lt;br /&gt;
&lt;br /&gt;
==More Examples==&lt;br /&gt;
See &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck for more examples.&lt;br /&gt;
&lt;br /&gt;
=Characteristics Of A Good Unit Test=&lt;br /&gt;
A good unit test has the following characteristics.&lt;br /&gt;
*It is important that the test executes fast. If the tests are slow, they will not be run often.&lt;br /&gt;
*Environmental dependencies such as databases, file systems, networks, queues, and so on which will slow down the tests are either separated or simulated. Tests that exercise these will not run fast, and a failure does not give meaningful feedback about what the problem actually is.&lt;br /&gt;
*The scope of testing is very limited. If the test fails, it's obvious where to look for the problem. It's important to only test one aspect in a single test.&lt;br /&gt;
*The test should run and pass in isolation (on any machine). If the tests require special environmental setup or fail unexpectedly, then they are not good unit tests.&lt;br /&gt;
*Such a test often uses stubs and mock objects. If the code being tested typically calls out to a database or file system, these dependencies must be simulated, or mocked. These dependencies will ordinarily be abstracted away by using interfaces.&lt;br /&gt;
*The intention of testing is clearly revealed. Another developer can look at the test and understand what is expected of the production code.&lt;br /&gt;
&lt;br /&gt;
=Benefits Of TDD=&lt;br /&gt;
*Automated testing: Automated system makes the testing much more easier and faster. Manual testing is slower and needs human interaction which is error-prone. Automated testing makes sure any particular test is not missing every time we test the system, whereas humans may leave a test out mistakenly during testing process.&lt;br /&gt;
*Better to test New/Modified Functionality: With manual testing whenever you add new functionality or modify existing functionality, QA personal needs to test all systems that may be affected due to the modification which may be time-consuming. This may also leave a hidden bug in the system after modification. With TDD whenever a new functionality is added or existing functionality is modified, the whole set of tests in the system is run to make sure existing tests are passed. This makes sure that existing functionality is not broken.&lt;br /&gt;
*Developer’s confidence: With TDD, developers are more safe to change the system as any inappropriate changes will make some tests to fail. With non-TDD system developers needs to take more care to change existing system as the new change may fail other functionality. But with TDD developers can do so easily as after modification if developer runs the test he/she will find immediately that the change has failed some other tests (i.e. some other part of the system).&lt;br /&gt;
*Manual testing stage is shortened: In non-TDD development, as soon as developers prepare a build, QA personal starts testing. This manual testing takes a reasonable amount of time and increases the time to deliver the product from the build time. With TDD, a major part of the system is tested during development and needs lesser QA involvement in the time between build and final delivery of the product.&lt;br /&gt;
*Alternative Documentation: Unit tests are kind of documentation to system. Each unit test tells about an individual requirement to the module or system. For example, the following test ensures that only a logged in user with proper balance can buy an item when the item exists in stock. This test reflects a user aspect scenario of the system.&lt;br /&gt;
&lt;br /&gt;
     public void CheckUserCanNotPurchaseItemWithoutBalance(){  &lt;br /&gt;
     LoginToTheSystem();       &lt;br /&gt;
     SelectAnItemToBuy();       &lt;br /&gt;
     MakeSureItemExsitsInStock();       &lt;br /&gt;
     MakeSureUserHasBalanceToBuy();      &lt;br /&gt;
     RunTheTransaction(); &lt;br /&gt;
  }			&lt;br /&gt;
*Better way to fix bugs: In TDD approach when QA finds a bug, developer first writes a test that generates the bug (that is the test will fail due to this bug). Then developer modifies code to make sure that the test is passed (i.e., the bug is fixed). This approach makes sure that next time the bug will not appear in the system as a test is written in the system to take care of the bug.&lt;br /&gt;
*Repetition of the same bug reduced: With TDD once a bug is found, it's put under test. So every time you run the whole test in the system, the tests associated with the bug are run and make sure the bugs are not generated again.&lt;br /&gt;
&lt;br /&gt;
=Shortcomings Of TDD=&lt;br /&gt;
*The actual database or external file is never tested directly by TDD (only production code can test it)&lt;br /&gt;
*If not used carefully, it can add to the total project costs and complexity of the project&lt;br /&gt;
*TDD is unable to test UI.&lt;br /&gt;
*TDD is highly reliant on Refactoring and Programmer Skills.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
Danielle&lt;br /&gt;
=References=&lt;br /&gt;
*[http://catalog.lib.ncsu.edu/record/NCSU1601963 Beck, K. (2002). Test-driven development by example. Addison-Wesley.]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Test_driven_development (n.d.). Test-driven development. website: http://en.wikipedia.org/wiki/Test_driven_development]&lt;br /&gt;
*[http://c2.com/cgi/wiki?TestDrivenDevelopment (2012, January 11). Test driven development. website: http://c2.com/cgi/wiki?TestDrivenDevelopment]&lt;br /&gt;
*[http://www.agiledata.org/essays/tdd.html Ambler, S. W. (2002). Introduction to test driven development (tdd). Retrieved from Agile Data website: http://www.agiledata.org/essays/tdd.html]&lt;br /&gt;
*[http://www.methodsandtools.com/archive/archive.php?id=20. Methods and Tools Archives]&lt;br /&gt;
*[http://www.martinfowler.com/bliki/TestDrivenDevelopment.html www.martinfowler.com/bliki/TestDrivenDevelopment]&lt;br /&gt;
*[http://www.codeproject.com/Articles/47747/Test-Driven-Development-TDD-Step-by-Step-Part-1-In TDD Step by Step Code Project]&lt;br /&gt;
*[http://integralpath.blogs.com/thinkingoutloud/2005/09/principles_of_t.html Principles of Testing]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=68179</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w11 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=68179"/>
		<updated>2012-10-25T16:54:57Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Introduction=&lt;br /&gt;
Test driven development (TDD) is a process that tries to create the minimal amount of code to meet customer's expectations. The idea is to test first, code second, then improve (or refactor) last. This process forces the software developers to focus on customer specifications and validation first. Since at each step of the way the programmer proves to himself that the code meets specifications, TDD gives the programmer confidence. The rest of this chapter gives the motivation for TDD, shows the steps for TDD, outlines the principles of TDD, provides examples using TDD, and compares the pros and cons of TDD.&lt;br /&gt;
&lt;br /&gt;
=Motivation for TDD=&lt;br /&gt;
[[File:TimevsCostDev.png|350px|Thumb:Figure 1: Traditional &amp;quot;Cost of Change&amp;quot; curve with the waterfall model superimposed]]&lt;br /&gt;
&lt;br /&gt;
*Testing is the one activity that improves the quality of code. In various design scenarios, like waterfall model, testing occurs towards the end of the project development activity. As shown in the figure 1, introducing testing as a latter phase increases the cost incurred for implementing the changes. From this we infer that there is a high chance of reducing the costs by moving the Test phase to the initial part.&lt;br /&gt;
*The client can also be well informed about the design and can suggest changes which can be incorporated well in advance. This approach also known as TDD helps achieve flexibility to achieve the client’s ever-changing requirements&lt;br /&gt;
&lt;br /&gt;
=Principles=&lt;br /&gt;
*Tests serve as examples of how to use a class or method.  Once used to having tests that show how things work (and that they work), developers start inquiring if a test was already there for the piece of code to be developed&lt;br /&gt;
*Developer tests are distinctly different from QA (Quality Analysis) tests and should be kept separate.  QA tests target features and treat the system as a black box.  Unit tests created by the developer operate at a lower level and test different things.&lt;br /&gt;
*Name the tests carefully.  For Example, name test packages like the package being tested with a suffix.  For example, the &amp;quot;DataAccess&amp;quot; project/package is tested by &amp;quot;DataAccess.Test&amp;quot;. Also,  name test classes the same as the class under test with the suffix &amp;quot;Test&amp;quot;.  For example, the class &amp;quot;PrintManager&amp;quot; is tested by the test class &amp;quot;PrintManagerTest&amp;quot;.  This convention makes it easy to find the related class and keeps the class name a noun. You should also name test methods the same as the method being tested with the prefix &amp;quot;Test&amp;quot;.  For example, the method &amp;quot;PrintProductOrder()&amp;quot; is tested by the method &amp;quot;TestPrintProductOrder()&amp;quot;.  This convention keeps the method name a verb that reads as an english phrase.  &lt;br /&gt;
*Write each test before writing the method under test. It encourages the developer to think as a user of the target method before thinking about implementation, which usually results in a cleaner, easier-to-use interface.&lt;br /&gt;
*Follow the &amp;quot;3-As&amp;quot; pattern for test methods: Arrange, Act, Assert. Specifically, use separate code paragraphs (groups of lines of code separated by a blank line) for each of the As.  Arrange is variable declaration and initialization.  Act is invoking the code under test.  Assert is using the Assert.* methods to verify that expectations were met. &lt;br /&gt;
*When writing application code, only write enough code to make a test work. This technique prevents gold-plating and ensures that you always have a test for the code you write. &lt;br /&gt;
*When you find you need to refractor working code, refractor and re-test prior to writing new code.  This technique ensures your refractoring is correct prior to adding new functionality and applies to creating new methods, introducing inheritance, everything.&lt;br /&gt;
=Steps=&lt;br /&gt;
&lt;br /&gt;
[[Image:PureFab.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Follow these steps:&lt;br /&gt;
*Understand the requirements of the story, work item, or feature that you are working on.&lt;br /&gt;
*Red:Create a test and make it fail.&lt;br /&gt;
Imagine how the new code should be called and write the test as if the code already existed.&lt;br /&gt;
Create the new production code stub. Write just enough code so that it compiles.&lt;br /&gt;
Run the test. It should fail. This is a calibration measure to ensure that your test is calling the correct code and that the code is not working by accident. This is a meaningful failure, and you expect it to fail.&lt;br /&gt;
*Green: Make the test pass by any means necessary.&lt;br /&gt;
Write the production code to make the test pass. Keep it simple.&lt;br /&gt;
Some advocate the hard-coding of the expected return value first to verify that the test correctly detects success. This varies from practitioner to practitioner.If you've written the code so that the test passes as intended, you are finished. You do not have to write more code speculatively. If new functionality is still needed, then another test is needed. Make this one test pass and continue.&lt;br /&gt;
When the test passes, you might want to run all tests up to this point to build confidence that everything else is still working.&lt;br /&gt;
*Refractor: Change the code to remove duplication in your project and to improve the design while ensuring that all tests still pass.&lt;br /&gt;
Remove duplication caused by the addition of the new functionality.&lt;br /&gt;
Make design changes to improve the overall solution.&lt;br /&gt;
After each refactoring, rerun all the tests to ensure that they all still pass.&lt;br /&gt;
*Repeat the cycle. Each cycle should be very short, and a typical hour should contain many Red/Green/ Refractor cycles.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
&lt;br /&gt;
==Homework Grades Program==&lt;br /&gt;
&lt;br /&gt;
===Setup===&lt;br /&gt;
As a simple example, we are creating a program that keeps track of our homework grades. We envision that we would be able to get the average of these homework grades. Step one: &amp;lt;b&amp;gt; write a test &amp;lt;/b&amp;gt;. Let's test an average function&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We will get multiple errors - this test won't even compile (but, that's ok for now). Let's take a look at what will generate error messages:&lt;br /&gt;
&lt;br /&gt;
* class &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; constructor not declared&lt;br /&gt;
* field &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* method &amp;lt;code&amp;gt;average&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
&lt;br /&gt;
Now, we fix the first error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Second error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Homework(void) {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Third error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int * grades;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fourth error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int average(int * grades) {&lt;br /&gt;
  return 0; // default return value&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, the test compiles! The code now looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
&lt;br /&gt;
    return 0; // default return value&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
Now, we run the test, and the familar red bar of failure greets us (remember the mantra red-green-refactor). The assert fails. The average function needs to actually average something (not just return 0). As we think about averaging the grades, we realize we need to know how many grades are in the int array &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt;. So, we add to the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
  int numGrades;                         // new&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
 &lt;br /&gt;
   int avg = 0;                         // new&lt;br /&gt;
 &lt;br /&gt;
   for(int i = 0; i &amp;lt; numGrades; i++) { // new&lt;br /&gt;
     avg += grades[i];                  // new&lt;br /&gt;
   }                                    // new&lt;br /&gt;
 &lt;br /&gt;
   return avg/numGrades;                // new&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Of course, we must remember to change the test to:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  myHomework.numGrades = 2;&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
Success! We have a green bar when we run it. &lt;br /&gt;
&lt;br /&gt;
===Refactor===&lt;br /&gt;
The last step is refactoring. Perhaps we don't want a grade to be an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;? Should it be an &amp;lt;code&amp;gt;unsigned int&amp;lt;/code&amp;gt;? For this simple example, there isn't much refactoring to do, but in a larger example there may be multiple areas for improvement.&lt;br /&gt;
&lt;br /&gt;
==Refactoring Example==&lt;br /&gt;
The following example is take from &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck.&lt;br /&gt;
&lt;br /&gt;
Using the TDD process the author created an object with the following structure:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dollar {&lt;br /&gt;
 &lt;br /&gt;
  Dollar(int amount) {&lt;br /&gt;
     this.amount = amount;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  void times(int mulitplier) {&lt;br /&gt;
    amount *= multiplier;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
What's wrong with the code above? Look at the following test:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  &lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  five.times(2);&lt;br /&gt;
  assertEquals(10, five.amount);&lt;br /&gt;
  five.times(3);&lt;br /&gt;
  assertEquals(15, five.amount);&lt;br /&gt;
&lt;br /&gt;
}  &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Whenever we perform an operation on a &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; the value of the &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; changes. In the test above &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; isn't 5 after we multiply it by 2, and thus the name &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; doesn't make sense anymore. How do we change this? &lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
&lt;br /&gt;
First, we change the &amp;lt;b&amp;gt;test&amp;lt;/b&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  Dollar product = five.times(2);&lt;br /&gt;
  assertEquals(10, product.amount);&lt;br /&gt;
  product = five.times(3);&lt;br /&gt;
  assertEquals(15, product.amount);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new test won't compile until we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  amount *= multiplier;&lt;br /&gt;
  return null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now the test compiles, but fails. Once again, we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  return new Dollar(amount * multiplier);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
&lt;br /&gt;
The test succeeds. So we see that even when we are refactoring we change the test first, then the code. This way we know our refactoring is an improvement.&lt;br /&gt;
&lt;br /&gt;
==More Examples==&lt;br /&gt;
See &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck for more examples.&lt;br /&gt;
&lt;br /&gt;
=Characteristics Of A Good Unit Test=&lt;br /&gt;
A good unit test has the following characteristics.&lt;br /&gt;
*It is important that the test executes fast. If the tests are slow, they will not be run often.&lt;br /&gt;
*Environmental dependencies such as databases, file systems, networks, queues, and so on which will slow down the tests are either separated or simulated. Tests that exercise these will not run fast, and a failure does not give meaningful feedback about what the problem actually is.&lt;br /&gt;
*The scope of testing is very limited. If the test fails, it's obvious where to look for the problem. It's important to only test one aspect in a single test.&lt;br /&gt;
*The test should run and pass in isolation (on any machine). If the tests require special environmental setup or fail unexpectedly, then they are not good unit tests.&lt;br /&gt;
*Such a test often uses stubs and mock objects. If the code being tested typically calls out to a database or file system, these dependencies must be simulated, or mocked. These dependencies will ordinarily be abstracted away by using interfaces.&lt;br /&gt;
*The intention of testing is clearly revealed. Another developer can look at the test and understand what is expected of the production code.&lt;br /&gt;
&lt;br /&gt;
=Benefits Of TDD=&lt;br /&gt;
*Automated testing: Automated system makes the testing much more easier and faster. Manual testing is slower and needs human interaction which is error-prone. Automated testing makes sure any particular test is not missing every time we test the system, whereas humans may leave a test out mistakenly during testing process.&lt;br /&gt;
*Better to test New/Modified Functionality: With manual testing whenever you add new functionality or modify existing functionality, QA personal needs to test all systems that may be affected due to the modification which may be time-consuming. This may also leave a hidden bug in the system after modification. With TDD whenever a new functionality is added or existing functionality is modified, the whole set of tests in the system is run to make sure existing tests are passed. This makes sure that existing functionality is not broken.&lt;br /&gt;
*Developer’s confidence: With TDD, developers are more safe to change the system as any inappropriate changes will make some tests to fail. With non-TDD system developers needs to take more care to change existing system as the new change may fail other functionality. But with TDD developers can do so easily as after modification if developer runs the test he/she will find immediately that the change has failed some other tests (i.e. some other part of the system).&lt;br /&gt;
*Manual testing stage is shortened: In non-TDD development, as soon as developers prepare a build, QA personal starts testing. This manual testing takes a reasonable amount of time and increases the time to deliver the product from the build time. With TDD, a major part of the system is tested during development and needs lesser QA involvement in the time between build and final delivery of the product.&lt;br /&gt;
*Alternative Documentation: Unit tests are kind of documentation to system. Each unit test tells about an individual requirement to the module or system. For example, the following test ensures that only a logged in user with proper balance can buy an item when the item exists in stock. This test reflects a user aspect scenario of the system.&lt;br /&gt;
&lt;br /&gt;
     public void CheckUserCanNotPurchaseItemWithoutBalance(){  &lt;br /&gt;
     LoginToTheSystem();       &lt;br /&gt;
     SelectAnItemToBuy();       &lt;br /&gt;
     MakeSureItemExsitsInStock();       &lt;br /&gt;
     MakeSureUserHasBalanceToBuy();      &lt;br /&gt;
     RunTheTransaction(); &lt;br /&gt;
  }			&lt;br /&gt;
*Better way to fix bugs: In TDD approach when QA finds a bug, developer first writes a test that generates the bug (that is the test will fail due to this bug). Then developer modifies code to make sure that the test is passed (i.e., the bug is fixed). This approach makes sure that next time the bug will not appear in the system as a test is written in the system to take care of the bug.&lt;br /&gt;
*Repetition of the same bug reduced: With TDD once a bug is found, it's put under test. So every time you run the whole test in the system, the tests associated with the bug are run and make sure the bugs are not generated again.&lt;br /&gt;
&lt;br /&gt;
=Shortcomings Of TDD=&lt;br /&gt;
*The actual database or external file is never tested directly by TDD (only production code can test it)&lt;br /&gt;
*If not used carefully, it can add to the total project costs and complexity of the project&lt;br /&gt;
*TDD is unable to test UI.&lt;br /&gt;
*TDD is highly reliant on Refactoring and Programmer Skills.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
Danielle&lt;br /&gt;
=References=&lt;br /&gt;
*[http://catalog.lib.ncsu.edu/record/NCSU1601963 Beck, K. (2002). Test-driven development by example. Addison-Wesley.]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Test_driven_development (n.d.). Test-driven development. website: http://en.wikipedia.org/wiki/Test_driven_development]&lt;br /&gt;
*[http://c2.com/cgi/wiki?TestDrivenDevelopment (2012, January 11). Test driven development. website: http://c2.com/cgi/wiki?TestDrivenDevelopment]&lt;br /&gt;
*[http://www.agiledata.org/essays/tdd.html Ambler, S. W. (2002). Introduction to test driven development (tdd). Retrieved from Agile Data website: http://www.agiledata.org/essays/tdd.html]&lt;br /&gt;
*[http://www.methodsandtools.com/archive/archive.php?id=20. Methods and Tools Archives]&lt;br /&gt;
*[http://www.martinfowler.com/bliki/TestDrivenDevelopment.html www.martinfowler.com/bliki/TestDrivenDevelopment]&lt;br /&gt;
*[http://www.codeproject.com/Articles/47747/Test-Driven-Development-TDD-Step-by-Step-Part-1-In TDD Step by Step Code Project]&lt;br /&gt;
*[http://integralpath.blogs.com/thinkingoutloud/2005/09/principles_of_t.html Principles of Testing]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=68178</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w11 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=68178"/>
		<updated>2012-10-25T16:54:11Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Introduction=&lt;br /&gt;
Test driven development (TDD) is a process that tries to create the minimal amount of code to meet customer's expectations. The idea is to test first, code second, then improve (or refactor) last. This process forces the software developers to focus on customer specifications and validation first. Since at each step of the way the programmer proves to himself that the code meets specifications, TDD gives the programmer confidence. The rest of this chapter gives the motivation for TDD, shows the steps for TDD, outlines the principles of TDD, provides examples using TDD, and compares the pros and cons of TDD.&lt;br /&gt;
&lt;br /&gt;
=Motivation for TDD=&lt;br /&gt;
[[File:TimevsCostDev.png|350px|Thumb:Figure 1: Traditional &amp;quot;Cost of Change&amp;quot; curve with the waterfall model superimposed]]&lt;br /&gt;
&lt;br /&gt;
*Testing is the one activity that improves the quality of code. In various design scenarios, like waterfall model, testing occurs towards the end of the project development activity. As shown in the figure 1, introducing testing as a latter phase increases the cost incurred for implementing the changes. From this we infer that there is a high chance of reducing the costs by moving the Test phase to the initial part.&lt;br /&gt;
*The client can also be well informed about the design and can suggest changes which can be incorporated well in advance. This approach also known as TDD helps achieve flexibility to achieve the client’s ever-changing requirements&lt;br /&gt;
&lt;br /&gt;
=Principles=&lt;br /&gt;
*Tests serve as examples of how to use a class or method.  Once used to having tests that show how things work (and that they work), developers start inquiring if a test was already there for the piece of code to be developed&lt;br /&gt;
*Developer tests are distinctly different from QA (Quality Analysis) tests and should be kept separate.  QA tests target features and treat the system as a black box.  Unit tests created by the developer operate at a lower level and test different things.&lt;br /&gt;
*Name the tests carefully.  For Example, name test packages like the package being tested with a suffix.  For example, the &amp;quot;DataAccess&amp;quot; project/package is tested by &amp;quot;DataAccess.Test&amp;quot;. Also,  name test classes the same as the class under test with the suffix &amp;quot;Test&amp;quot;.  For example, the class &amp;quot;PrintManager&amp;quot; is tested by the test class &amp;quot;PrintManagerTest&amp;quot;.  This convention makes it easy to find the related class and keeps the class name a noun. You should also name test methods the same as the method being tested with the prefix &amp;quot;Test&amp;quot;.  For example, the method &amp;quot;PrintProductOrder()&amp;quot; is tested by the method &amp;quot;TestPrintProductOrder()&amp;quot;.  This convention keeps the method name a verb that reads as an english phrase.  &lt;br /&gt;
*Write each test before writing the method under test. It encourages the developer to think as a user of the target method before thinking about implementation, which usually results in a cleaner, easier-to-use interface.&lt;br /&gt;
*Follow the &amp;quot;3-As&amp;quot; pattern for test methods: Arrange, Act, Assert. Specifically, use separate code paragraphs (groups of lines of code separated by a blank line) for each of the As.  Arrange is variable declaration and initialization.  Act is invoking the code under test.  Assert is using the Assert.* methods to verify that expectations were met. &lt;br /&gt;
*When writing application code, only write enough code to make a test work. This technique prevents gold-plating and ensures that you always have a test for the code you write. &lt;br /&gt;
*When you find you need to refractor working code, refractor and re-test prior to writing new code.  This technique ensures your refractoring is correct prior to adding new functionality and applies to creating new methods, introducing inheritance, everything.&lt;br /&gt;
=Steps=&lt;br /&gt;
&lt;br /&gt;
[[Image:PureFab.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Follow these steps:&lt;br /&gt;
*Understand the requirements of the story, work item, or feature that you are working on.&lt;br /&gt;
*Red:Create a test and make it fail.&lt;br /&gt;
Imagine how the new code should be called and write the test as if the code already existed.&lt;br /&gt;
Create the new production code stub. Write just enough code so that it compiles.&lt;br /&gt;
Run the test. It should fail. This is a calibration measure to ensure that your test is calling the correct code and that the code is not working by accident. This is a meaningful failure, and you expect it to fail.&lt;br /&gt;
*Green: Make the test pass by any means necessary.&lt;br /&gt;
Write the production code to make the test pass. Keep it simple.&lt;br /&gt;
Some advocate the hard-coding of the expected return value first to verify that the test correctly detects success. This varies from practitioner to practitioner.If you've written the code so that the test passes as intended, you are finished. You do not have to write more code speculatively. If new functionality is still needed, then another test is needed. Make this one test pass and continue.&lt;br /&gt;
When the test passes, you might want to run all tests up to this point to build confidence that everything else is still working.&lt;br /&gt;
*Refractor: Change the code to remove duplication in your project and to improve the design while ensuring that all tests still pass.&lt;br /&gt;
Remove duplication caused by the addition of the new functionality.&lt;br /&gt;
Make design changes to improve the overall solution.&lt;br /&gt;
After each refactoring, rerun all the tests to ensure that they all still pass.&lt;br /&gt;
*Repeat the cycle. Each cycle should be very short, and a typical hour should contain many Red/Green/ Refractor cycles.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
&lt;br /&gt;
==Homework Grades Program==&lt;br /&gt;
&lt;br /&gt;
===Setup===&lt;br /&gt;
As a simple example, we are creating a program that keeps track of our homework grades. We envision that we would be able to get the average of these homework grades. Step one: &amp;lt;b&amp;gt; write a test &amp;lt;/b&amp;gt;. Let's test an average function&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We will get multiple errors - this test won't even compile (but, that's ok for now). Let's take a look at what will generate error messages:&lt;br /&gt;
&lt;br /&gt;
* class &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; constructor not declared&lt;br /&gt;
* field &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* method &amp;lt;code&amp;gt;average&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
&lt;br /&gt;
Now, we fix the first error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Second error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Homework(void) {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Third error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int * grades;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fourth error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int average(int * grades) {&lt;br /&gt;
  return 0; // default return value&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, the test compiles! The code now looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
&lt;br /&gt;
    return 0; // default return value&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
Now, we run the test, and the familar red bar of failure greets us (remember the mantra red-green-refactor). The assert fails. The average function needs to actually average something (not just return 0). As we think about averaging the grades, we realize we need to know how many grades are in the int array &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt;. So, we add to the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
  int numGrades;                         // new&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
 &lt;br /&gt;
   int avg = 0;                         // new&lt;br /&gt;
 &lt;br /&gt;
   for(int i = 0; i &amp;lt; numGrades; i++) { // new&lt;br /&gt;
     avg += grades[i];                  // new&lt;br /&gt;
   }                                    // new&lt;br /&gt;
 &lt;br /&gt;
   return avg/numGrades;                // new&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Of course, we must remember to change the test to:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  myHomework.numGrades = 2;&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
Success! We have a green bar when we run it. &lt;br /&gt;
&lt;br /&gt;
===Refactor===&lt;br /&gt;
The last step is refactoring. Perhaps we don't want a grade to be an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;? Should it be an &amp;lt;code&amp;gt;unsigned int&amp;lt;/code&amp;gt;? For this simple example, there isn't much refactoring to do, but in a larger example there may be multiple areas for improvement.&lt;br /&gt;
&lt;br /&gt;
==Refactoring Example==&lt;br /&gt;
The following example is take from &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck.&lt;br /&gt;
&lt;br /&gt;
Using the TDD process the author created an object with the following structure:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dollar {&lt;br /&gt;
 &lt;br /&gt;
  Dollar(int amount) {&lt;br /&gt;
     this.amount = amount;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  void times(int mulitplier) {&lt;br /&gt;
    amount *= multiplier;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
What's wrong with the code above? Look at the following test:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  &lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  five.times(2);&lt;br /&gt;
  assertEquals(10, five.amount);&lt;br /&gt;
  five.times(3);&lt;br /&gt;
  assertEquals(15, five.amount);&lt;br /&gt;
&lt;br /&gt;
}  &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Whenever we perform an operation on a &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; the value of the &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; changes. In the test above &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; isn't 5 after we multiply it by 2, and thus the name &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; doesn't make sense anymore. How do we change this? &lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
&lt;br /&gt;
First, we change the &amp;lt;b&amp;gt;test&amp;lt;/b&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  Dollar product = five.times(2);&lt;br /&gt;
  assertEquals(10, product.amount);&lt;br /&gt;
  product = five.times(3);&lt;br /&gt;
  assertEquals(15, product.amount);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new test won't compile until we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  amount *= multiplier;&lt;br /&gt;
  return null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now the test compiles, but fails. Once again, we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  return new Dollar(amount * multiplier);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
&lt;br /&gt;
The test succeeds. So we see that even when we are refactoring we change the test first, then the code. This way we know our refactoring is an improvement.&lt;br /&gt;
&lt;br /&gt;
==More Examples==&lt;br /&gt;
See &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck for more examples.&lt;br /&gt;
&lt;br /&gt;
=Characteristics Of A Good Unit Test=&lt;br /&gt;
A good unit test has the following characteristics.&lt;br /&gt;
*It is important that the test executes fast. If the tests are slow, they will not be run often.&lt;br /&gt;
*Environmental dependencies such as databases, file systems, networks, queues, and so on which will slow down the tests are either separated or simulated. Tests that exercise these will not run fast, and a failure does not give meaningful feedback about what the problem actually is.&lt;br /&gt;
*The scope of testing is very limited. If the test fails, it's obvious where to look for the problem. It's important to only test one aspect in a single test.&lt;br /&gt;
*The test should run and pass in isolation (on any machine). If the tests require special environmental setup or fail unexpectedly, then they are not good unit tests.&lt;br /&gt;
*Such a test often uses stubs and mock objects. If the code being tested typically calls out to a database or file system, these dependencies must be simulated, or mocked. These dependencies will ordinarily be abstracted away by using interfaces.&lt;br /&gt;
*The intention of testing is clearly revealed. Another developer can look at the test and understand what is expected of the production code.&lt;br /&gt;
&lt;br /&gt;
=Benefits Of TDD=&lt;br /&gt;
*Automated testing: Automated system makes the testing much more easier and faster. Manual testing is slower and needs human interaction which is error-prone. Automated testing makes sure any particular test is not missing every time we test the system, whereas humans may leave a test out mistakenly during testing process.&lt;br /&gt;
*Better to test New/Modified Functionality: With manual testing whenever you add new functionality or modify existing functionality, QA personal needs to test all systems that may be affected due to the modification which may be time-consuming. This may also leave a hidden bug in the system after modification. With TDD whenever a new functionality is added or existing functionality is modified, the whole set of tests in the system is run to make sure existing tests are passed. This makes sure that existing functionality is not broken.&lt;br /&gt;
*Developer’s confidence: With TDD, developers are more safe to change the system as any inappropriate changes will make some tests to fail. With non-TDD system developers needs to take more care to change existing system as the new change may fail other functionality. But with TDD developers can do so easily as after modification if developer runs the test he/she will find immediately that the change has failed some other tests (i.e. some other part of the system).&lt;br /&gt;
*Manual testing stage is shortened: In non-TDD development, as soon as developers prepare a build, QA personal starts testing. This manual testing takes a reasonable amount of time and increases the time to deliver the product from the build time. With TDD, a major part of the system is tested during development and needs lesser QA involvement in the time between build and final delivery of the product.&lt;br /&gt;
*Alternative Documentation: Unit tests are kind of documentation to system. Each unit test tells about an individual requirement to the module or system. For example, the following test ensures that only a logged in user with proper balance can buy an item when the item exists in stock. This test reflects a user aspect scenario of the system.&lt;br /&gt;
&lt;br /&gt;
     public void CheckUserCanNotPurchaseItemWithoutBalance(){  &lt;br /&gt;
     LoginToTheSystem();       &lt;br /&gt;
     SelectAnItemToBuy();       &lt;br /&gt;
     MakeSureItemExsitsInStock();       &lt;br /&gt;
     MakeSureUserHasBalanceToBuy();      &lt;br /&gt;
     RunTheTransaction(); &lt;br /&gt;
  }			&lt;br /&gt;
*Better way to fix bugs: In TDD approach when QA finds a bug, developer first writes a test that generates the bug (that is the test will fail due to this bug). Then developer modifies code to make sure that the test is passed (i.e., the bug is fixed). This approach makes sure that next time the bug will not appear in the system as a test is written in the system to take care of the bug.&lt;br /&gt;
*Repetition of the same bug reduced: With TDD once a bug is found, it's put under test. So every time you run the whole test in the system, the tests associated with the bug are run and make sure the bugs are not generated again.&lt;br /&gt;
&lt;br /&gt;
=Shortcomings Of TDD=&lt;br /&gt;
*The actual database or external file is never tested directly by TDD (only production code can test it)&lt;br /&gt;
*If not used carefully, it can add to the total project costs and complexity of the project&lt;br /&gt;
*TDD is unable to test UI.&lt;br /&gt;
*TDD is highly reliant on Refactoring and Programmer Skills.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
Danielle&lt;br /&gt;
=References=&lt;br /&gt;
*[http://catalog.lib.ncsu.edu/record/NCSU1601963 Beck, K. (2002). Test-driven development by example. Addison-Wesley.]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Test_driven_development (n.d.). Test-driven development. website: http://en.wikipedia.org/wiki/Test_driven_development]&lt;br /&gt;
*[http://c2.com/cgi/wiki?TestDrivenDevelopment (2012, January 11). Test driven development. website: http://c2.com/cgi/wiki?TestDrivenDevelopment]&lt;br /&gt;
*[http://www.agiledata.org/essays/tdd.html Ambler, S. W. (2002). Introduction to test driven development (tdd). Retrieved from Agile Data website: http://www.agiledata.org/essays/tdd.html]&lt;br /&gt;
*[http://www.methodsandtools.com/archive/archive.php?id=20. Methods and Tools Archives]&lt;br /&gt;
*[http://www.martinfowler.com/bliki/TestDrivenDevelopment.html www.martinfowler.com/bliki/TestDrivenDevelopment]&lt;br /&gt;
*[http://www.codeproject.com/Articles/47747/Test-Driven-Development-TDD-Step-by-Step-Part-1-In TDD Step by Step Code Project]&lt;br /&gt;
*[http://integralpath.blogs.com/thinkingoutloud/2005/09/principles_of_t.html Principles of Testing]&lt;br /&gt;
*http://www.testdriven.com/  ?&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=68177</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w11 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=68177"/>
		<updated>2012-10-25T16:51:25Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Examples */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Introduction=&lt;br /&gt;
Test driven development (TDD) is a process that tries to create the minimal amount of code to meet customer's expectations. The idea is to test first, code second, then improve (or refactor) last. This process forces the software developers to focus on customer specifications and validation first. Since at each step of the way the programmer proves to himself that the code meets specifications, TDD gives the programmer confidence. The rest of this chapter gives the motivation for TDD, shows the steps for TDD, outlines the principles of TDD, and provides examples using TDD.&lt;br /&gt;
&lt;br /&gt;
=Motivation for TDD=&lt;br /&gt;
[[File:TimevsCostDev.png|350px|Thumb:Figure 1: Traditional &amp;quot;Cost of Change&amp;quot; curve with the waterfall model superimposed]]&lt;br /&gt;
&lt;br /&gt;
*Testing is the one activity that improves the quality of code. In various design scenarios, like waterfall model, testing occurs towards the end of the project development activity. As shown in the figure 1, introducing testing as a latter phase increases the cost incurred for implementing the changes. From this we infer that there is a high chance of reducing the costs by moving the Test phase to the initial part.&lt;br /&gt;
*The client can also be well informed about the design and can suggest changes which can be incorporated well in advance. This approach also known as TDD helps achieve flexibility to achieve the client’s ever-changing requirements&lt;br /&gt;
&lt;br /&gt;
=Principles=&lt;br /&gt;
*Tests serve as examples of how to use a class or method.  Once used to having tests that show how things work (and that they work), developers start inquiring if a test was already there for the piece of code to be developed&lt;br /&gt;
*Developer tests are distinctly different from QA (Quality Analysis) tests and should be kept separate.  QA tests target features and treat the system as a black box.  Unit tests created by the developer operate at a lower level and test different things.&lt;br /&gt;
*Name the tests carefully.  For Example, name test packages like the package being tested with a suffix.  For example, the &amp;quot;DataAccess&amp;quot; project/package is tested by &amp;quot;DataAccess.Test&amp;quot;. Also,  name test classes the same as the class under test with the suffix &amp;quot;Test&amp;quot;.  For example, the class &amp;quot;PrintManager&amp;quot; is tested by the test class &amp;quot;PrintManagerTest&amp;quot;.  This convention makes it easy to find the related class and keeps the class name a noun. You should also name test methods the same as the method being tested with the prefix &amp;quot;Test&amp;quot;.  For example, the method &amp;quot;PrintProductOrder()&amp;quot; is tested by the method &amp;quot;TestPrintProductOrder()&amp;quot;.  This convention keeps the method name a verb that reads as an english phrase.  &lt;br /&gt;
*Write each test before writing the method under test. It encourages the developer to think as a user of the target method before thinking about implementation, which usually results in a cleaner, easier-to-use interface.&lt;br /&gt;
*Follow the &amp;quot;3-As&amp;quot; pattern for test methods: Arrange, Act, Assert. Specifically, use separate code paragraphs (groups of lines of code separated by a blank line) for each of the As.  Arrange is variable declaration and initialization.  Act is invoking the code under test.  Assert is using the Assert.* methods to verify that expectations were met. &lt;br /&gt;
*When writing application code, only write enough code to make a test work. This technique prevents gold-plating and ensures that you always have a test for the code you write. &lt;br /&gt;
*When you find you need to refractor working code, refractor and re-test prior to writing new code.  This technique ensures your refractoring is correct prior to adding new functionality and applies to creating new methods, introducing inheritance, everything.&lt;br /&gt;
=Steps=&lt;br /&gt;
&lt;br /&gt;
[[Image:PureFab.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Follow these steps:&lt;br /&gt;
*Understand the requirements of the story, work item, or feature that you are working on.&lt;br /&gt;
*Red:Create a test and make it fail.&lt;br /&gt;
Imagine how the new code should be called and write the test as if the code already existed.&lt;br /&gt;
Create the new production code stub. Write just enough code so that it compiles.&lt;br /&gt;
Run the test. It should fail. This is a calibration measure to ensure that your test is calling the correct code and that the code is not working by accident. This is a meaningful failure, and you expect it to fail.&lt;br /&gt;
*Green: Make the test pass by any means necessary.&lt;br /&gt;
Write the production code to make the test pass. Keep it simple.&lt;br /&gt;
Some advocate the hard-coding of the expected return value first to verify that the test correctly detects success. This varies from practitioner to practitioner.If you've written the code so that the test passes as intended, you are finished. You do not have to write more code speculatively. If new functionality is still needed, then another test is needed. Make this one test pass and continue.&lt;br /&gt;
When the test passes, you might want to run all tests up to this point to build confidence that everything else is still working.&lt;br /&gt;
*Refractor: Change the code to remove duplication in your project and to improve the design while ensuring that all tests still pass.&lt;br /&gt;
Remove duplication caused by the addition of the new functionality.&lt;br /&gt;
Make design changes to improve the overall solution.&lt;br /&gt;
After each refactoring, rerun all the tests to ensure that they all still pass.&lt;br /&gt;
*Repeat the cycle. Each cycle should be very short, and a typical hour should contain many Red/Green/ Refractor cycles.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
&lt;br /&gt;
==Homework Grades Program==&lt;br /&gt;
&lt;br /&gt;
===Setup===&lt;br /&gt;
As a simple example, we are creating a program that keeps track of our homework grades. We envision that we would be able to get the average of these homework grades. Step one: &amp;lt;b&amp;gt; write a test &amp;lt;/b&amp;gt;. Let's test an average function&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We will get multiple errors - this test won't even compile (but, that's ok for now). Let's take a look at what will generate error messages:&lt;br /&gt;
&lt;br /&gt;
* class &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; constructor not declared&lt;br /&gt;
* field &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* method &amp;lt;code&amp;gt;average&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
&lt;br /&gt;
Now, we fix the first error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Second error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Homework(void) {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Third error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int * grades;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fourth error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int average(int * grades) {&lt;br /&gt;
  return 0; // default return value&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, the test compiles! The code now looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
&lt;br /&gt;
    return 0; // default return value&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
Now, we run the test, and the familar red bar of failure greets us (remember the mantra red-green-refactor). The assert fails. The average function needs to actually average something (not just return 0). As we think about averaging the grades, we realize we need to know how many grades are in the int array &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt;. So, we add to the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
  int numGrades;                         // new&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
 &lt;br /&gt;
   int avg = 0;                         // new&lt;br /&gt;
 &lt;br /&gt;
   for(int i = 0; i &amp;lt; numGrades; i++) { // new&lt;br /&gt;
     avg += grades[i];                  // new&lt;br /&gt;
   }                                    // new&lt;br /&gt;
 &lt;br /&gt;
   return avg/numGrades;                // new&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Of course, we must remember to change the test to:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  myHomework.numGrades = 2;&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
Success! We have a green bar when we run it. &lt;br /&gt;
&lt;br /&gt;
===Refactor===&lt;br /&gt;
The last step is refactoring. Perhaps we don't want a grade to be an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;? Should it be an &amp;lt;code&amp;gt;unsigned int&amp;lt;/code&amp;gt;? For this simple example, there isn't much refactoring to do, but in a larger example there may be multiple areas for improvement.&lt;br /&gt;
&lt;br /&gt;
==Refactoring Example==&lt;br /&gt;
The following example is take from &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck.&lt;br /&gt;
&lt;br /&gt;
Using the TDD process the author created an object with the following structure:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dollar {&lt;br /&gt;
 &lt;br /&gt;
  Dollar(int amount) {&lt;br /&gt;
     this.amount = amount;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  void times(int mulitplier) {&lt;br /&gt;
    amount *= multiplier;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
What's wrong with the code above? Look at the following test:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  &lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  five.times(2);&lt;br /&gt;
  assertEquals(10, five.amount);&lt;br /&gt;
  five.times(3);&lt;br /&gt;
  assertEquals(15, five.amount);&lt;br /&gt;
&lt;br /&gt;
}  &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Whenever we perform an operation on a &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; the value of the &amp;lt;code&amp;gt;Dollar&amp;lt;/code&amp;gt; changes. In the test above &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; isn't 5 after we multiply it by 2, and thus the name &amp;lt;code&amp;gt;five&amp;lt;/code&amp;gt; doesn't make sense anymore. How do we change this? &lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
&lt;br /&gt;
First, we change the &amp;lt;b&amp;gt;test&amp;lt;/b&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void testMultiplication() {&lt;br /&gt;
  Dollar five = new Dollar(5);&lt;br /&gt;
  Dollar product = five.times(2);&lt;br /&gt;
  assertEquals(10, product.amount);&lt;br /&gt;
  product = five.times(3);&lt;br /&gt;
  assertEquals(15, product.amount);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new test won't compile until we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  amount *= multiplier;&lt;br /&gt;
  return null;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now the test compiles, but fails. Once again, we change the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Dollar times(int multiplier) {&lt;br /&gt;
  return new Dollar(amount * multiplier);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
&lt;br /&gt;
The test succeeds. So we see that even when we are refactoring we change the test first, then the code. This way we know our refactoring is an improvement.&lt;br /&gt;
&lt;br /&gt;
==More Examples==&lt;br /&gt;
See &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck for more examples.&lt;br /&gt;
&lt;br /&gt;
=Characteristics Of A Good Unit Test=&lt;br /&gt;
A good unit test has the following characteristics.&lt;br /&gt;
*It is important that the test executes fast. If the tests are slow, they will not be run often.&lt;br /&gt;
*Environmental dependencies such as databases, file systems, networks, queues, and so on which will slow down the tests are either separated or simulated. Tests that exercise these will not run fast, and a failure does not give meaningful feedback about what the problem actually is.&lt;br /&gt;
*The scope of testing is very limited. If the test fails, it's obvious where to look for the problem. It's important to only test one aspect in a single test.&lt;br /&gt;
*The test should run and pass in isolation (on any machine). If the tests require special environmental setup or fail unexpectedly, then they are not good unit tests.&lt;br /&gt;
*Such a test often uses stubs and mock objects. If the code being tested typically calls out to a database or file system, these dependencies must be simulated, or mocked. These dependencies will ordinarily be abstracted away by using interfaces.&lt;br /&gt;
*The intention of testing is clearly revealed. Another developer can look at the test and understand what is expected of the production code.&lt;br /&gt;
&lt;br /&gt;
=Benefits Of TDD=&lt;br /&gt;
*Automated testing: Automated system makes the testing much more easier and faster. Manual testing is slower and needs human interaction which is error-prone. Automated testing makes sure any particular test is not missing every time we test the system, whereas humans may leave a test out mistakenly during testing process.&lt;br /&gt;
*Better to test New/Modified Functionality: With manual testing whenever you add new functionality or modify existing functionality, QA personal needs to test all systems that may be affected due to the modification which may be time-consuming. This may also leave a hidden bug in the system after modification. With TDD whenever a new functionality is added or existing functionality is modified, the whole set of tests in the system is run to make sure existing tests are passed. This makes sure that existing functionality is not broken.&lt;br /&gt;
*Developer’s confidence: With TDD, developers are more safe to change the system as any inappropriate changes will make some tests to fail. With non-TDD system developers needs to take more care to change existing system as the new change may fail other functionality. But with TDD developers can do so easily as after modification if developer runs the test he/she will find immediately that the change has failed some other tests (i.e. some other part of the system).&lt;br /&gt;
*Manual testing stage is shortened: In non-TDD development, as soon as developers prepare a build, QA personal starts testing. This manual testing takes a reasonable amount of time and increases the time to deliver the product from the build time. With TDD, a major part of the system is tested during development and needs lesser QA involvement in the time between build and final delivery of the product.&lt;br /&gt;
*Alternative Documentation: Unit tests are kind of documentation to system. Each unit test tells about an individual requirement to the module or system. For example, the following test ensures that only a logged in user with proper balance can buy an item when the item exists in stock. This test reflects a user aspect scenario of the system.&lt;br /&gt;
&lt;br /&gt;
     public void CheckUserCanNotPurchaseItemWithoutBalance(){  &lt;br /&gt;
     LoginToTheSystem();       &lt;br /&gt;
     SelectAnItemToBuy();       &lt;br /&gt;
     MakeSureItemExsitsInStock();       &lt;br /&gt;
     MakeSureUserHasBalanceToBuy();      &lt;br /&gt;
     RunTheTransaction(); &lt;br /&gt;
  }			&lt;br /&gt;
*Better way to fix bugs: In TDD approach when QA finds a bug, developer first writes a test that generates the bug (that is the test will fail due to this bug). Then developer modifies code to make sure that the test is passed (i.e., the bug is fixed). This approach makes sure that next time the bug will not appear in the system as a test is written in the system to take care of the bug.&lt;br /&gt;
*Repetition of the same bug reduced: With TDD once a bug is found, it's put under test. So every time you run the whole test in the system, the tests associated with the bug are run and make sure the bugs are not generated again.&lt;br /&gt;
&lt;br /&gt;
=Shortcomings Of TDD=&lt;br /&gt;
*The actual database or external file is never tested directly by TDD (only production code can test it)&lt;br /&gt;
*If not used carefully, it can add to the total project costs and complexity of the project&lt;br /&gt;
*TDD is unable to test UI.&lt;br /&gt;
*TDD is highly reliant on Refactoring and Programmer Skills.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
Danielle&lt;br /&gt;
=References=&lt;br /&gt;
*[http://catalog.lib.ncsu.edu/record/NCSU1601963 Beck, K. (2002). Test-driven development by example. Addison-Wesley.]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Test_driven_development (n.d.). Test-driven development. website: http://en.wikipedia.org/wiki/Test_driven_development]&lt;br /&gt;
*[http://c2.com/cgi/wiki?TestDrivenDevelopment (2012, January 11). Test driven development. website: http://c2.com/cgi/wiki?TestDrivenDevelopment]&lt;br /&gt;
*[http://www.agiledata.org/essays/tdd.html Ambler, S. W. (2002). Introduction to test driven development (tdd). Retrieved from Agile Data website: http://www.agiledata.org/essays/tdd.html]&lt;br /&gt;
*[http://www.methodsandtools.com/archive/archive.php?id=20. Methods and Tools Archives]&lt;br /&gt;
*[http://www.martinfowler.com/bliki/TestDrivenDevelopment.html www.martinfowler.com/bliki/TestDrivenDevelopment]&lt;br /&gt;
*[http://www.codeproject.com/Articles/47747/Test-Driven-Development-TDD-Step-by-Step-Part-1-In TDD Step by Step Code Project]&lt;br /&gt;
*[http://integralpath.blogs.com/thinkingoutloud/2005/09/principles_of_t.html Principles of Testing]&lt;br /&gt;
*http://www.testdriven.com/  ?&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=67823</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w11 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=67823"/>
		<updated>2012-10-22T15:41:12Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Examples */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Introduction=&lt;br /&gt;
Test driven development (TDD) is a process that tries to create the minimal amount of code to meet customer's expectations. The idea is to test first, code second, then improve (or refactor) last. This process forces the software developers to focus on customer specifications and validation first. Since at each step of the way the programmer proves to himself that the code meets specifications, TDD gives the programmer confidence. The rest of this chapter gives the motivation for TDD, shows the steps for TDD, outlines the principles of TDD, and provides examples using TDD.&lt;br /&gt;
&lt;br /&gt;
=Motivation for TDD=&lt;br /&gt;
Annice&lt;br /&gt;
=Steps=&lt;br /&gt;
Annice&lt;br /&gt;
=Principles=&lt;br /&gt;
Annice&lt;br /&gt;
=Examples=&lt;br /&gt;
&lt;br /&gt;
==Homework Grades Program==&lt;br /&gt;
&lt;br /&gt;
===Setup===&lt;br /&gt;
As a simple example, we are creating a program that keeps track of our homework grades. We envision that we would be able to get the average of these homework grades. Step one: &amp;lt;b&amp;gt; write a test &amp;lt;/b&amp;gt;. Let's test an average function&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We will get multiple errors - this test won't even compile (but, that's ok for now). Let's take a look at what will generate error messages:&lt;br /&gt;
&lt;br /&gt;
* class &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; constructor not declared&lt;br /&gt;
* field &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* method &amp;lt;code&amp;gt;average&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
&lt;br /&gt;
Now, we fix the first error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Second error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Homework(void) {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Third error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int * grades;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fourth error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int average(int * grades) {&lt;br /&gt;
  return 0; // default return value&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, the test compiles! The code now looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
&lt;br /&gt;
    return 0; // default return value&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
Now, we run the test, and the familar red bar of failure greets us (remember the mantra red-green-refactor). The assert fails. The average function needs to actually average something (not just return 0). As we think about averaging the grades, we realize we need to know how many grades are in the int array &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt;. So, we add to the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
  int numGrades;                         // new&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
 &lt;br /&gt;
   int avg = 0;                         // new&lt;br /&gt;
 &lt;br /&gt;
   for(int i = 0; i &amp;lt; numGrades; i++) { // new&lt;br /&gt;
     avg += grades[i];                  // new&lt;br /&gt;
   }                                    // new&lt;br /&gt;
 &lt;br /&gt;
   return avg/numGrades;                // new&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Of course, we must remember to change the test to:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  myHomework.numGrades = 2;&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
Success! We have a green bar when we run it. &lt;br /&gt;
&lt;br /&gt;
===Refactor===&lt;br /&gt;
The last step is refactoring. Perhaps we don't want a grade to be an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;? Should it be an &amp;lt;code&amp;gt;unsigned int&amp;lt;/code&amp;gt;? For this simple example, there isn't much refactoring to do, but in a larger example there may be multiple areas for improvement.&lt;br /&gt;
&lt;br /&gt;
==More Examples==&lt;br /&gt;
See &amp;lt;i&amp;gt;Test-Driven Development by Example&amp;lt;/i&amp;gt; by Kent Beck for more examples.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
Danielle&lt;br /&gt;
=References=&lt;br /&gt;
*[http://catalog.lib.ncsu.edu/record/NCSU1601963 Beck, K. (2002). Test-driven development by example. Addison-Wesley.]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Test_driven_development (n.d.). Test-driven development. website: http://en.wikipedia.org/wiki/Test_driven_development]&lt;br /&gt;
*[http://c2.com/cgi/wiki?TestDrivenDevelopment (2012, January 11). Test driven development. website: http://c2.com/cgi/wiki?TestDrivenDevelopment]&lt;br /&gt;
*[http://www.agiledata.org/essays/tdd.html Ambler, S. W. (2002). Introduction to test driven development (tdd). Retrieved from Agile Data website: http://www.agiledata.org/essays/tdd.html]&lt;br /&gt;
*http://www.testdriven.com/  ?&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=67821</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w11 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=67821"/>
		<updated>2012-10-22T15:14:39Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Examples */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Introduction=&lt;br /&gt;
Test driven development (TDD) is a process that tries to create the minimal amount of code to meet customer's expectations. The idea is to test first, code second, then improve (or refactor) last. This process forces the software developers to focus on customer specifications and validation first. Since at each step of the way the programmer proves to himself that the code meets specifications, TDD gives the programmer confidence. The rest of this chapter gives the motivation for TDD, shows the steps for TDD, outlines the principles of TDD, and provides examples using TDD.&lt;br /&gt;
&lt;br /&gt;
=Motivation for TDD=&lt;br /&gt;
Annice&lt;br /&gt;
=Steps=&lt;br /&gt;
Annice&lt;br /&gt;
=Principles=&lt;br /&gt;
Annice&lt;br /&gt;
=Examples=&lt;br /&gt;
&lt;br /&gt;
==Homework Grades Program==&lt;br /&gt;
&lt;br /&gt;
===Setup===&lt;br /&gt;
As a simple example, we are creating a program that keeps track of our homework grades. We envision that we would be able to get the average of these homework grades. Step one: &amp;lt;b&amp;gt; write a test &amp;lt;/b&amp;gt;. Let's test an average function&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We will get multiple errors - this test won't even compile (but, that's ok for now). Let's take a look at what will generate error messages:&lt;br /&gt;
&lt;br /&gt;
* class &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* &amp;lt;code&amp;gt;Homework&amp;lt;/code&amp;gt; constructor not declared&lt;br /&gt;
* field &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
* method &amp;lt;code&amp;gt;average&amp;lt;/code&amp;gt; not declared&lt;br /&gt;
&lt;br /&gt;
Now, we fix the first error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Second error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Homework(void) {&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Third error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int * grades;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fourth error:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
int average(int * grades) {&lt;br /&gt;
  return 0; // default return value&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Finally, the test compiles! The code now looks like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
&lt;br /&gt;
    return 0; // default return value&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Red===&lt;br /&gt;
Now, we run the test, and the familar red bar of failure greets us (remember the mantra red-green-refactor). The assert fails. The average function needs to actually average something (not just return 0). As we think about averaging the grades, we realize we need to know how many grades are in the int array &amp;lt;code&amp;gt;grades&amp;lt;/code&amp;gt;. So, we add to the code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Homework {&lt;br /&gt;
&lt;br /&gt;
  int * grades;&lt;br /&gt;
  int numGrades;                         // new&lt;br /&gt;
&lt;br /&gt;
  Homework(void) {&lt;br /&gt;
&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  int average(int * grades) {&lt;br /&gt;
 &lt;br /&gt;
   int avg = 0;                         // new&lt;br /&gt;
 &lt;br /&gt;
   for(int i = 0; i &amp;lt; numGrades; i++) { // new&lt;br /&gt;
     avg += grades[i];                  // new&lt;br /&gt;
   }                                    // new&lt;br /&gt;
 &lt;br /&gt;
   return avg/numGrades;                // new&lt;br /&gt;
 &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Of course, we must remember to change the test to:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  myHomework = new Homework();&lt;br /&gt;
  myHomework.grades = [100, 50];&lt;br /&gt;
  myHomework.numGrades = 2;&lt;br /&gt;
  assert(myHomework.average(myHomework.grades) == 75);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Green===&lt;br /&gt;
Success! We have a green bar when we run it. &lt;br /&gt;
&lt;br /&gt;
===Refactor===&lt;br /&gt;
The last step is refactoring. Perhaps we don't want a grade to be an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;? Should it be an &amp;lt;code&amp;gt;unsigned int&amp;lt;/code&amp;gt;? For this simple example, there isn't much refactoring to do, but in a larger example there may be multiple areas for improvement.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
Danielle&lt;br /&gt;
=References=&lt;br /&gt;
*[http://catalog.lib.ncsu.edu/record/NCSU1601963 Beck, K. (2002). Test-driven development by example. Addison-Wesley.]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Test_driven_development (n.d.). Test-driven development. website: http://en.wikipedia.org/wiki/Test_driven_development]&lt;br /&gt;
*[http://c2.com/cgi/wiki?TestDrivenDevelopment (2012, January 11). Test driven development. website: http://c2.com/cgi/wiki?TestDrivenDevelopment]&lt;br /&gt;
*[http://www.agiledata.org/essays/tdd.html Ambler, S. W. (2002). Introduction to test driven development (tdd). Retrieved from Agile Data website: http://www.agiledata.org/essays/tdd.html]&lt;br /&gt;
*http://www.testdriven.com/  ?&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=67820</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w11 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=67820"/>
		<updated>2012-10-22T14:08:01Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Introduction=&lt;br /&gt;
Test driven development (TDD) is a process that tries to create the minimal amount of code to meet customer's expectations. The idea is to test first, code second, then improve (or refactor) last. This process forces the software developers to focus on customer specifications and validation first. Since at each step of the way the programmer proves to himself that the code meets specifications, TDD gives the programmer confidence. The rest of this chapter gives the motivation for TDD, shows the steps for TDD, outlines the principles of TDD, and provides examples using TDD.&lt;br /&gt;
&lt;br /&gt;
=Motivation for TDD=&lt;br /&gt;
Annice&lt;br /&gt;
=Steps=&lt;br /&gt;
Annice&lt;br /&gt;
=Principles=&lt;br /&gt;
Annice&lt;br /&gt;
=Examples=&lt;br /&gt;
Danielle&lt;br /&gt;
=Conclusion=&lt;br /&gt;
Danielle&lt;br /&gt;
=References=&lt;br /&gt;
*[http://catalog.lib.ncsu.edu/record/NCSU1601963 Beck, K. (2002). Test-driven development by example. Addison-Wesley.]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Test_driven_development (n.d.). Test-driven development. website: http://en.wikipedia.org/wiki/Test_driven_development]&lt;br /&gt;
*[http://c2.com/cgi/wiki?TestDrivenDevelopment (2012, January 11). Test driven development. website: http://c2.com/cgi/wiki?TestDrivenDevelopment]&lt;br /&gt;
*[http://www.agiledata.org/essays/tdd.html Ambler, S. W. (2002). Introduction to test driven development (tdd). Retrieved from Agile Data website: http://www.agiledata.org/essays/tdd.html]&lt;br /&gt;
*http://www.testdriven.com/  ?&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=67819</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w11 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=67819"/>
		<updated>2012-10-22T13:45:27Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Introduction=&lt;br /&gt;
Test driven development (TDD) is a process that tries to create the minimal amount of code to meet customer's expectations. The idea is to test first, code second, then improve (or refactor) last. This process forces the software developers to focus on customer specifications and validation first. Since at each step of the way the programmer proves to himself that the code meets specifications, TDD gives the programmer confidence. The rest of this chapter gives the motivation for TDD, shows the steps for TDD, outlines the principles of TDD, and provides examples using TDD.&lt;br /&gt;
&lt;br /&gt;
=Motivation for TDD=&lt;br /&gt;
Annice&lt;br /&gt;
=Steps=&lt;br /&gt;
Annice&lt;br /&gt;
=Principles=&lt;br /&gt;
Annice&lt;br /&gt;
=Examples=&lt;br /&gt;
Danielle&lt;br /&gt;
=Conclusion=&lt;br /&gt;
Danielle&lt;br /&gt;
=References=&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012&amp;diff=67818</id>
		<title>CSC/ECE 517 Fall 2012</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012&amp;diff=67818"/>
		<updated>2012-10-22T13:24:59Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*[[CSC/ECE 517 Fall 2012/ch1 n xx]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w1 rk]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w20 pp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w5 su]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w6 pp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w4 aj]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w7 am]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w8 aa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w9 av]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w10 pk]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w11 ap]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1a 1w12 mv]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w14 gv]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w17 ir]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w18 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w22 an]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w21 aa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w21 wi]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w31 sa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1a 1w16 br]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1a 1w23 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w24 nr]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w15 rt]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w3 pl]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w32 cm]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w5 dp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w37 ss]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w67 ks]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w27 ms]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w29 sa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w33 op]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w19 sa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w34 vd]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w35 sa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w30 rp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w58 am]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w47 sk]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w69 mv]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w44 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w45 is]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w53 kc]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w40 ar]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w39 sn]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w54 go]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w56 ms]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w64 nn]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w66 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w40 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w42 js]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w46 sm]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w71 gs]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w63 dv]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w55 ms]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w57 mp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w52 an]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch1b 1w38 nm]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w60 ac]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w62 rb]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w29 st]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w30 an]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w17 pt]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w31 up]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w9 ms]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w19 is]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w5 dp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w16 dp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w8 vp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w18 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w3 jm]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w23 sr]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w11_aa]]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=67817</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w11 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w11_aa&amp;diff=67817"/>
		<updated>2012-10-22T13:24:01Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: Draft of organization&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Introduction=&lt;br /&gt;
Danielle&lt;br /&gt;
=Motivation for TDD=&lt;br /&gt;
Annice&lt;br /&gt;
=Steps=&lt;br /&gt;
Annice&lt;br /&gt;
=Principles=&lt;br /&gt;
Annice&lt;br /&gt;
=Examples=&lt;br /&gt;
Danielle&lt;br /&gt;
=Conclusion=&lt;br /&gt;
Danielle&lt;br /&gt;
=References=&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=65314</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=65314"/>
		<updated>2012-09-20T00:19:12Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Mixing Functional and Object-Oriented Programming */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
This wiki page explores the idea of mixing functional and object-oriented code. Mixing different [http://en.wikipedia.org/wiki/Multi-paradigm#Multi-paradigm_programming_language programming paradigms] is called multi-paradigm programming. There are four major paradigms:&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_paradigm Procedural/imperative paradigms]: Assembly, C, C++, Java, C#&lt;br /&gt;
* Object Oriented paradigm : C++, Java, Python, Ruby, Scala, C#&lt;br /&gt;
* Functional Paradigm : Lisp, Haskell, Clojure, Scala, OCaml, Ruby&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logic Paradigm]: Prolog&lt;br /&gt;
&lt;br /&gt;
In this wiki we explain how functional and object-oriented paradigms can be mixed. First, we explain what functional and object-oriented style programming is. Secondly, we will show how to apply functional techniques to object-oriented programming. Lastly, we discuss languages that support mixing functional and object-oriented code.&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and mandates that data is [http://en.wikipedia.org/wiki/Immutable immutable]. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
== Example Contrasting Imperitive and Functional Styles ==&lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily. &lt;br /&gt;
&lt;br /&gt;
== Advantages of Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-oriented Programming =&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm organized around interacting &amp;quot;objects&amp;quot;(usually instances of a class) rather than &amp;quot;actions&amp;quot; and data rather than logic. A basic principle of OOP is that a program consists of a list of subroutines which can perform individually. &lt;br /&gt;
&lt;br /&gt;
An object-oriented programming language provides support for the following object-oriented concepts--object, class, interface and inheritance. To illustrate this idea clearly and vividly let's review the following example-- your limbs. The &amp;quot;Limbs&amp;quot; is a class. Your body has two objects of type &amp;quot;limbs&amp;quot;, named arms and legs. Their main functions are controlled/ managed by a set of biological signals sent from central nervous system( through an interface). So the nervous system is an interface which your body uses to interact with your limbs. The &amp;quot;limbs&amp;quot; is a well architected class. The &amp;quot;legs&amp;quot; has a subclass which contains &amp;quot;left leg&amp;quot; and &amp;quot;Right leg&amp;quot;. The &amp;quot;legs&amp;quot; is being re-used to create the left leg and right leg by slightly changing the properties of it. If the &amp;quot;legs&amp;quot; owns attributes like length, color of skin etc, then the subclass, which contains &amp;quot;left leg&amp;quot; and &amp;quot;right leg&amp;quot; in this case, automatically inherit these attributes( that is called inheritance).&lt;br /&gt;
&lt;br /&gt;
We could code in object-oriented paradigm as:&lt;br /&gt;
&lt;br /&gt;
  class Limbs  &lt;br /&gt;
  #define a class of limbs&lt;br /&gt;
    def initialize(limbs,length,colorofskin)&lt;br /&gt;
    @limbs=limbs&lt;br /&gt;
    @length=length&lt;br /&gt;
    @colorofskin=colorofskin&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  limbs=Limbs.new(&amp;quot;legs&amp;quot;,&amp;quot;100cm&amp;quot;,&amp;quot;white&amp;quot;)  &lt;br /&gt;
  #create a new object in class &amp;quot;Limbs&amp;quot;&lt;br /&gt;
  class Legs&amp;lt;Limbs   &lt;br /&gt;
  #create a subclass &amp;quot;Legs&amp;quot;,which belong to class&amp;quot;Limbs&amp;quot;&lt;br /&gt;
    def initialize(legs,length,colorofskin)&lt;br /&gt;
      super(length,colorofskin)&lt;br /&gt;
      @legs=legs&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
  legs=legs.new(&amp;quot;left leg&amp;quot;) &lt;br /&gt;
  #create a new object in class of &amp;quot;Legs&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Features of Object-oriented Programming ==&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]. A programmer can simply create a new object that inherits many of its features from super-class. And also, they can overwrite existing operations or add new ones.This makes object-oriented programs easier to modify.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation].This refers to hiding the internal representation of the object from the outside view. You can hide unnecessary implementation details from the object user. One of the benefits of encapsulation is data protection.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism].This allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Consider the operator '+', for numbers it will generate the sum, but for strings it will produce a third string which concatenates the input strings.&lt;br /&gt;
&lt;br /&gt;
== Advantages of Object-oriented Programming ==&lt;br /&gt;
* Simplicity: we use software objects to simulate real world objects, so the complexity is reduced and the program structure is very clear.&lt;br /&gt;
* Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.&lt;br /&gt;
* Modifiability: programmers can easily make minor changes in the data representation or operations in an OOP. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.&lt;br /&gt;
* Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.&lt;br /&gt;
* Maintainability: objects can be maintained separately, making locating and fixing problems easier.&lt;br /&gt;
* Re-usability: objects can be reused in different programs.&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
In object-oriented world, data and operations are grouped together into modular units called objects and we combine objects into structured networks to form a program. The results are depend on arguments and objects' state at method invocation time. While in functional world, the basic elements are variables in the mathematical sense and functions in the mathematical sense. Functional programming can reduce side-effects. If there is no side-effects, it means your can apply the function at anywhere freely. No matter how you apply this function, the same input arguments produce the same results.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Functional - Mathematical Functions&lt;br /&gt;
!  Object-Oriented - Objects&lt;br /&gt;
|-&lt;br /&gt;
| Compact&lt;br /&gt;
| Modular&lt;br /&gt;
|-&lt;br /&gt;
| Easy to debug&lt;br /&gt;
| Easy to maintain&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Overall, object-oriented programming requires more upfront design, but is easier to maintain long-term. Obviously if we apply functional programming techniques to object-oriented programming, everything can be done better--the code is easier to write, runs faster, and uses less memory.&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
According to above-mentioned information, we can perform functional programming on an object-oriented programming language because:&lt;br /&gt;
1). object can have constant state &lt;br /&gt;
2). method can depend only on its arguments and context available at method definition time&lt;br /&gt;
&lt;br /&gt;
Combining both these paradigms not only provide us a robust design structure, but also enable the programmers to develop solutions to complex problems quickly and effectively. One of the cornerstone of mixing functional and object-oriented code is treating functions as objects.It means that we can pass functions as arguments, store it and return them from other functions. This is highly useful in an user interface code where it can be used as call back functions which gets called when an event occurs(event driven programming).&lt;br /&gt;
&lt;br /&gt;
Some of the basic features of Functional Programming which can be combined with Object Oriented paradigm are:&lt;br /&gt;
&lt;br /&gt;
* Lambda Calculus&lt;br /&gt;
* Currying&lt;br /&gt;
* Powerful pattern matching&lt;br /&gt;
&lt;br /&gt;
Let us now understand how each of the above feature of Functional language fits in the Object Oriented paradigm.&lt;br /&gt;
&lt;br /&gt;
=== Lambda Calculus ===&lt;br /&gt;
Lambda calculus is the most critical basis of functional programming. A lambda expression is an anonymous expression that contain expressions and statements.Each expression stands for a function with one parameter. &lt;br /&gt;
&lt;br /&gt;
Let consider the following function:&lt;br /&gt;
&lt;br /&gt;
  def f(x)&lt;br /&gt;
  return x**2 &lt;br /&gt;
  print f(4)&lt;br /&gt;
&lt;br /&gt;
We can use a lambda calculus to compute this expression without assigning it to a variable: &lt;br /&gt;
&lt;br /&gt;
  (lambda x:x**x)(4)  &lt;br /&gt;
&lt;br /&gt;
We can see that these two code snippets have the same results. It is more concise and flexible to define with lambda.&lt;br /&gt;
The above is a pure functional approach. In order to make code more state-less and concise, lambdas can be embedded inside the object-oriented language. The below code in Python demonstrates the use of lambda in a closure:&lt;br /&gt;
&lt;br /&gt;
  def fun(x):&lt;br /&gt;
    return x%3==0&lt;br /&gt;
    str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
    filter(fun,str)&lt;br /&gt;
&lt;br /&gt;
The above code works to find numbers which are divisible by 3.&lt;br /&gt;
We can simplify the code by the use of lambda as following:&lt;br /&gt;
&lt;br /&gt;
  str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
  print filter(lambda x: x%3==0, str)&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
In the above information we have learned much about lambda calculus, which take care of one argument, now let me introduce you another concept called currying functions which takes in multiple arguments and returns a chain of functions with lesser number of arguments. It can be interpreted as the technique to decompose a function that takes n parameters into n functions and each of the n functions takes one parameter. &lt;br /&gt;
&lt;br /&gt;
Currying is really an interesting concept. Let's take a sample code in JavaScript to understand it: &lt;br /&gt;
&lt;br /&gt;
  //This is a function for calculating x+y. The difference between this function and general is that this is a currying function.&lt;br /&gt;
  function add(x, y)&lt;br /&gt;
  {&lt;br /&gt;
  if(x!=null &amp;amp;&amp;amp; y!=null) return x + y;&lt;br /&gt;
  else if(x!=null &amp;amp;&amp;amp; y==null) return function(y)&lt;br /&gt;
   { &lt;br /&gt;
     return x + y;  //return a closure with parameter y for subsequent calculations&lt;br /&gt;
    }&lt;br /&gt;
  else if(x==null &amp;amp;&amp;amp; y!=null) return function(x)&lt;br /&gt;
   {&lt;br /&gt;
     return x + y;  //return a closure with parameter x for subsequent calculations&lt;br /&gt;
    }&lt;br /&gt;
   }&lt;br /&gt;
  var a = add(3, 4);  //compute the value of (3+4) and return the value of 7&lt;br /&gt;
  var b = add(2);  //add(2) is equal to a function of (2+y)&lt;br /&gt;
  var c = b(10);  //pass 10 to y, and return the value of (2+10) which is 12&lt;br /&gt;
&lt;br /&gt;
In the above sample, b=add(2) gives us a currying function of add(), which is function of y when x=2.&lt;br /&gt;
&lt;br /&gt;
More interestingly, we can define a currying form of arbitrary functions.&lt;br /&gt;
  function Foo(x, y, z, w)&lt;br /&gt;
  {&lt;br /&gt;
   var args = arguments;&lt;br /&gt;
   if(Foo.length &amp;lt; args.length)&lt;br /&gt;
     return function()&lt;br /&gt;
    {&lt;br /&gt;
      return args.callee.apply(Array.apply([], args).concat(Array.apply([], arguments)));&lt;br /&gt;
    }&lt;br /&gt;
   else&lt;br /&gt;
     return x + y – z * w;&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
What is pattern matching? I think all of you do know what it is, you just don't know you know it. The semantics are equally straightforward.Firstly, we evaluate the value expression, then we walk down the clauses. For each one, we see if the pattern matches the value. If so, we execute the body and end. Simply put, pattern matching is a technique to search string for the occurrence of any patterns or regularity. &lt;br /&gt;
&lt;br /&gt;
Pattern matching allows you to do different calculations according to different identifier values. It looks the same with nests of &amp;quot;if...else&amp;quot; statements, as well as &amp;quot;switch&amp;quot; statements in C++ and C#. But here it is much stronger and more flexible. &lt;br /&gt;
&lt;br /&gt;
You may find that there are two main types of usage of pattern matching:&lt;br /&gt;
* To search and find a particular value.&lt;br /&gt;
* To find a particular value and replace it with selected text. &lt;br /&gt;
&lt;br /&gt;
For example, the following code snippets writes a message if a string contains the text Perl or Python:&lt;br /&gt;
&lt;br /&gt;
  if line =~ /Perl|Python/&lt;br /&gt;
  puts &amp;quot;Scripting language mentioned:#{line}&amp;quot;  &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Next, let us consider the following sample in which a part of a string matched by a regular expression can be replaced with different text using one of Ruby’s substitution methods:&lt;br /&gt;
&lt;br /&gt;
  line.sub(/Perl/, 'Ruby') # replace first 'Perl' with 'Ruby'&lt;br /&gt;
  line.gsub(/Python/, 'Ruby') # replace every 'Python' with 'Ruby'&lt;br /&gt;
&lt;br /&gt;
Advantages of Pattern Matching:&lt;br /&gt;
* It allows concise, readable deconstruction of complex data structures.&lt;br /&gt;
* It gives a possible separation of data structure and respective functionality.&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
A number of programming languages support mixing of both functional and object-oriented code. Three of these (Scala, Ruby, and Conjure), are described in more detail below.&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky. It supports mixing functional and object-oriented code.&lt;br /&gt;
&lt;br /&gt;
==== Mixing Functional and Object-Oriented Code in Scala ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object-oriented and functional programming. How can this happen? The functional world advocates immutability, but the object-oriented world focuses on the state and how to change it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . A rough translation into Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as:&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks much simpler and less verbose. Even though the above example shows an immutable collection, scala also provides mutable collections and object types in the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So it's the best of both worlds. Another part of the functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
==== Implicits in Scala ====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. Since you are splitting open the class and adding/overriding methods (in)|(to) the class, this feature is often called [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching]. Because other libraries may depend on some methods which you changed, often this leads to unexpected behavior at runtime. However, Scala provides yet another feature called [http://en.wikipedia.org/wiki/Implicit_function implicits] which helps you do this better.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Ruby is another language that, like Scala, supports mixing functional and object-oriented code. It is a dynamically typed Object-Oriented Language which supports multiple programming paradigms, including functional, object-oriented, imperative and reflective. In Ruby, everything is an object, every bit of information and code can have its own properties and actions. However, Ruby’s blocks can be functional. A Ruby programmer can attach a closure to any method, which generates a functional block inside an object oriented code. A closure is a piece of code that can access the lexical environment of its definition [http://www.ruby-lang.org/en/ 11].&lt;br /&gt;
&lt;br /&gt;
==== Ruby Mixing Example ====&lt;br /&gt;
&lt;br /&gt;
Consider the following code snippet in Ruby which uses Object Oriented concepts like Classes and functional programming concepts like lambda.&lt;br /&gt;
&lt;br /&gt;
 class Multiply&lt;br /&gt;
   def initialize(n)&lt;br /&gt;
     @block = lambda {|a| n * a}&lt;br /&gt;
   end&lt;br /&gt;
   def mul(a)&lt;br /&gt;
     @block.call a&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 twoMultiplier = Multiply.new 2                     &lt;br /&gt;
 puts twoMultiplier.mul(6)&lt;br /&gt;
&lt;br /&gt;
Here,'''''@block''''' is a closure. When we call the class ''Multiply'' using '''''twoAdder = Multiply.new 2''''' ,the ''initialize'' method is called by passing the parameter 2. Here n=2 binds itself to the block. So @block will be 2*a, that is,the closure remembers the parameter with which the initialize method was called even after the initialize method exits.  &lt;br /&gt;
&lt;br /&gt;
This value is used when the block is called in the add method.  &lt;br /&gt;
Thus,'''''twoMultiplier.mul(6)''''' will return 2*6 = 12&lt;br /&gt;
&lt;br /&gt;
==== Functional Style Coding in Ruby Blocks ====&lt;br /&gt;
&lt;br /&gt;
Blocks are basically nameless functions which can be passed to a function and then that function can invoke the passed in nameless function. This is a common style called [http://en.wikipedia.org/wiki/Higher-order_function higher order functions] among languages that handle functions as first class objects. Basically blocks can be designed for loop abstraction and lets the user to design their own way of iterating the values, thereby hiding the implementation details. &lt;br /&gt;
For example, if we want to iterate backwards from the end to the beginning without revealing its internal implementations, we could implement the loop logic inside the block and pass it to a method or function.&lt;br /&gt;
&lt;br /&gt;
Here is a [http://www.ruby-lang.org/en/ Ruby] implementation of block:&lt;br /&gt;
 &lt;br /&gt;
 def printlist(array,&amp;amp;reverse)&lt;br /&gt;
    array.each do |element|&lt;br /&gt;
       puts &amp;quot;array element: #{element}&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
    reverse.call(array)   /* Here it prints the reverse implementation of list*/&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
 printlist([1,2,3,4,5,6]) { |array| &lt;br /&gt;
   array.reverse.each do |element| &lt;br /&gt;
     puts &amp;quot;array element: #{element}&amp;quot; &lt;br /&gt;
   end &lt;br /&gt;
 }&lt;br /&gt;
The statements between { } is a block and it gets called by &amp;lt;code&amp;gt;reverse.call(array)&amp;lt;/code&amp;gt;within the printlist method.&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 31]] is also a functional programming language, and it is a dialect of Lisp. It is not a pure functional language. Instead, it is a dynamically typed language. Just like Java it runs on JVM platform, but its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
(functions arguments...)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The function and its arguments are enclosed in paranthesis. It has features like immutable data structures, high-order functions, recursion, and easy and fast java interoperability. &lt;br /&gt;
&lt;br /&gt;
In Clojure's model, value calculation is purely functional. Values never change. New values are functions of old. But, logical identity is well supported via atomic references to values. The value of a reference (state of an identity) is always observable without coordination and freely shareable between threads.&lt;br /&gt;
When programs are constructed this way, functional value calculation is independent of identity-value association. This makes clojure easier to understand and test.&lt;br /&gt;
&lt;br /&gt;
====Example Using Functional Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
Consider the following functional programming example in Clojure-&lt;br /&gt;
 (defn make-adder [x]&lt;br /&gt;
   (let [y x]&lt;br /&gt;
     (fn [z] (+ y z))))&lt;br /&gt;
 (def add2 (make-adder 2))&lt;br /&gt;
 (add2 4)&lt;br /&gt;
&lt;br /&gt;
Here,'''''defn make-adder [x]''''' defines a function called ''make-adder''.'''''let [y x]''''' gives a local name y for the value x. Since the scope of any local names is lexical, a function created in the scope of local names will close over their values.'''''fn [z] (+ y z)''''' does the addition of y and z.&lt;br /&gt;
''&lt;br /&gt;
'''def add2 (make-adder 2)''''' calls the function ''make-adder'' passing the parameter 2 and calls this as ''add2''.Now, ''add2'' has computed 2+z. When '''''add2 4''''' is called it computes 2+4=6&lt;br /&gt;
&lt;br /&gt;
====Example Using Object-Oriented Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
The following program implements Run-Time Polymorphism which is an object-oriented programming concept.&lt;br /&gt;
 (defmulti encounter (fn [x y] [(:Species x) (:Species y)]))&lt;br /&gt;
 (defmethod encounter [:Bunny :Lion] [b l] :run-away)&lt;br /&gt;
 (defmethod encounter [:Lion :Bunny] [l b] :eat)&lt;br /&gt;
 (defmethod encounter [:Lion :Lion] [l1 l2] :fight)&lt;br /&gt;
 (defmethod encounter [:Bunny :Bunny] [b1 b2] :mate)&lt;br /&gt;
 (def b1 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def b2 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def l1 {:Species :Lion :other :stuff})&lt;br /&gt;
 (def l2 {:Species :Lion :other :stuff})&lt;br /&gt;
 &lt;br /&gt;
 (encounter b1 l1)&lt;br /&gt;
 -&amp;gt; :run-away&lt;br /&gt;
 (encounter l1 l2)&lt;br /&gt;
 -&amp;gt; :fight&lt;br /&gt;
&lt;br /&gt;
Here,'''''defmulti''''' is used to define multiple methods which have the same method name '''''encounter'''''.Depending on the parameters passed to the encounter method, one of the four methods is called.&lt;br /&gt;
'''''def''''' defines each of the different species.&lt;br /&gt;
When, '''''(encounter b1 l1)''''' is called, the first ''encounter'' method is called with the parameters ''Bunny'' and ''Lion''. As a result, ''run-away'' is printed.&lt;br /&gt;
&lt;br /&gt;
=== Summary of Languages Supporting Mixing ===&lt;br /&gt;
&lt;br /&gt;
Each of the languages contains both functional and object-oriented features. The following table shows how each of the languages have both functional and object-oriented characterics. Not all characteristics of the languages are listed, but enough to demonstrate that the languages each have different ways of mixing object-oriented and functional techniques.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  &lt;br /&gt;
!  Functional Characteristics&lt;br /&gt;
!  Object-Oriented Characteristics&lt;br /&gt;
|-&lt;br /&gt;
! Scala&lt;br /&gt;
| Immutable objects, the ability to pass functions as parameters, implicits, closures.&lt;br /&gt;
| Every value is a object, mutable objects.&lt;br /&gt;
|-&lt;br /&gt;
! Ruby&lt;br /&gt;
| Functional programming used in blocks.&lt;br /&gt;
| Everything is an object.&lt;br /&gt;
|-&lt;br /&gt;
! Clojure&lt;br /&gt;
| Immutable data structures, high-order functions, recursion.&lt;br /&gt;
| Objects, runtime polymorphism, [http://en.wikipedia.org/wiki/Multiple_dispatch multimethods.]&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
In summary, functional and object-oriented programming can be successfully mixed in programs. Many functional techniques are useful in object-oriented programs. Functional programming integrated with object oriented style leads to: &lt;br /&gt;
&lt;br /&gt;
*Better understanding of program behavior and easier debugging as a result of immutability features&lt;br /&gt;
*Use of techniques such as blocks and closures to implement object oriented design and reduce repetitive code&lt;br /&gt;
*Lesser complexity and reduction in the number of lines of code &lt;br /&gt;
&lt;br /&gt;
Languages such as Scala, Ruby, and Clojure effectively support mixing these two paradigms, allowing programmers to create cleaner, less buggy object-oriented code.&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
Special thanks to writers of previous wiki pages (see last three references below).&lt;br /&gt;
&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Functional_programming Wikipedia - Functional Programming]&lt;br /&gt;
#[http://www.cs.cornell.edu/riccardo/prog-smlnj/notes-011001.pdf Notes on programming Standard ML of New Jersey]&lt;br /&gt;
#[http://users.dickinson.edu/~braught/courses/cs132f01/classes/code/Factorial.src.html Introduction to Computing - Dickinson College]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Object-oriented_programming Wikipedia - Object Oriented Programming]&lt;br /&gt;
#[http://searchsoa.techtarget.com/sDefinition/0,,sid26_gci212681,00.html  More on Object Oriented Programming]&lt;br /&gt;
#[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas Understanding Ruby Blocks, Procs and Lambdas - Robert Sosinski]&lt;br /&gt;
#[http://www.codingday.com/power-of-functional-programming-its-features-and-its-future/ Power of Functional Programming, its Features and its Future]&lt;br /&gt;
#[http://skillsmatter.com/podcast/open-source-dot-net/mike-wagg-mark-needham-functional-and-oo-approaches-to-c-sharp-programming Mixing Functional and Object Oriented Approaches to Programming in C#]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigm]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Recursion Recursion]&lt;br /&gt;
#[http://www.scala-lang.org/ Scala]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Scala_%28programming_language%29 Scala Wikipedia]&lt;br /&gt;
#[http://clojure.org/ Clojure]&lt;br /&gt;
#[http://www.ruby-lang.org/en/ Ruby]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Standard_ML Standard ML]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Haskell_%28programming_language%29 Haskell]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/ML_%28programming_language%29 ML Family]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/C%2B%2B C++ Programming Language]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Visual_Basic_.NET Visual Basic .Net]&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;br /&gt;
#O'Reilly (2009), &amp;quot;Programming Scala&amp;quot;, ''O'Reilly Media Inc.''.&lt;br /&gt;
#Dave Thomas, Chad Fowler, Andy Hunt (2006) ''Programming Ruby'', The Pragmatic Bookshelf.&lt;br /&gt;
#[http://lamp.epfl.ch/~phaller/doc/haller10-Translucent_functions.pdf Philipp Halle, Lightweight language support for type-based, concurrent event processing, Lausanne, Switzerland, April 2010.]&lt;br /&gt;
#[http://biblion.epfl.ch/EPFL/theses/2007/3899/EPFL_TH3899.pdf Burak Emir, Object-Oriented Pattern Matching, EPFL, October 2007].&lt;br /&gt;
#[http://math.hws.edu/eck/cs124/downloads/OOP2_from_Univ_KwaZulu-Natal.pdf, Object-Oriented Programming,February 2007].&lt;br /&gt;
#[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_1e_az CSC/ECE 517 Fall 2010/ch1 1e az]&lt;br /&gt;
#[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_1e_AE CSC/ECE 517 Fall 2010/ch1 1e AE]&lt;br /&gt;
#[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_1e_bb CSC/ECE 517 Fall 2010/ch1 1e bb]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=65313</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=65313"/>
		<updated>2012-09-20T00:18:56Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: Added side-by-side comparison of Functional/Object-oriented advantages.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
This wiki page explores the idea of mixing functional and object-oriented code. Mixing different [http://en.wikipedia.org/wiki/Multi-paradigm#Multi-paradigm_programming_language programming paradigms] is called multi-paradigm programming. There are four major paradigms:&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_paradigm Procedural/imperative paradigms]: Assembly, C, C++, Java, C#&lt;br /&gt;
* Object Oriented paradigm : C++, Java, Python, Ruby, Scala, C#&lt;br /&gt;
* Functional Paradigm : Lisp, Haskell, Clojure, Scala, OCaml, Ruby&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logic Paradigm]: Prolog&lt;br /&gt;
&lt;br /&gt;
In this wiki we explain how functional and object-oriented paradigms can be mixed. First, we explain what functional and object-oriented style programming is. Secondly, we will show how to apply functional techniques to object-oriented programming. Lastly, we discuss languages that support mixing functional and object-oriented code.&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and mandates that data is [http://en.wikipedia.org/wiki/Immutable immutable]. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
== Example Contrasting Imperitive and Functional Styles ==&lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily. &lt;br /&gt;
&lt;br /&gt;
== Advantages of Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-oriented Programming =&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm organized around interacting &amp;quot;objects&amp;quot;(usually instances of a class) rather than &amp;quot;actions&amp;quot; and data rather than logic. A basic principle of OOP is that a program consists of a list of subroutines which can perform individually. &lt;br /&gt;
&lt;br /&gt;
An object-oriented programming language provides support for the following object-oriented concepts--object, class, interface and inheritance. To illustrate this idea clearly and vividly let's review the following example-- your limbs. The &amp;quot;Limbs&amp;quot; is a class. Your body has two objects of type &amp;quot;limbs&amp;quot;, named arms and legs. Their main functions are controlled/ managed by a set of biological signals sent from central nervous system( through an interface). So the nervous system is an interface which your body uses to interact with your limbs. The &amp;quot;limbs&amp;quot; is a well architected class. The &amp;quot;legs&amp;quot; has a subclass which contains &amp;quot;left leg&amp;quot; and &amp;quot;Right leg&amp;quot;. The &amp;quot;legs&amp;quot; is being re-used to create the left leg and right leg by slightly changing the properties of it. If the &amp;quot;legs&amp;quot; owns attributes like length, color of skin etc, then the subclass, which contains &amp;quot;left leg&amp;quot; and &amp;quot;right leg&amp;quot; in this case, automatically inherit these attributes( that is called inheritance).&lt;br /&gt;
&lt;br /&gt;
We could code in object-oriented paradigm as:&lt;br /&gt;
&lt;br /&gt;
  class Limbs  &lt;br /&gt;
  #define a class of limbs&lt;br /&gt;
    def initialize(limbs,length,colorofskin)&lt;br /&gt;
    @limbs=limbs&lt;br /&gt;
    @length=length&lt;br /&gt;
    @colorofskin=colorofskin&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  limbs=Limbs.new(&amp;quot;legs&amp;quot;,&amp;quot;100cm&amp;quot;,&amp;quot;white&amp;quot;)  &lt;br /&gt;
  #create a new object in class &amp;quot;Limbs&amp;quot;&lt;br /&gt;
  class Legs&amp;lt;Limbs   &lt;br /&gt;
  #create a subclass &amp;quot;Legs&amp;quot;,which belong to class&amp;quot;Limbs&amp;quot;&lt;br /&gt;
    def initialize(legs,length,colorofskin)&lt;br /&gt;
      super(length,colorofskin)&lt;br /&gt;
      @legs=legs&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
  legs=legs.new(&amp;quot;left leg&amp;quot;) &lt;br /&gt;
  #create a new object in class of &amp;quot;Legs&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Features of Object-oriented Programming ==&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]. A programmer can simply create a new object that inherits many of its features from super-class. And also, they can overwrite existing operations or add new ones.This makes object-oriented programs easier to modify.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation].This refers to hiding the internal representation of the object from the outside view. You can hide unnecessary implementation details from the object user. One of the benefits of encapsulation is data protection.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism].This allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Consider the operator '+', for numbers it will generate the sum, but for strings it will produce a third string which concatenates the input strings.&lt;br /&gt;
&lt;br /&gt;
== Advantages of Object-oriented Programming ==&lt;br /&gt;
* Simplicity: we use software objects to simulate real world objects, so the complexity is reduced and the program structure is very clear.&lt;br /&gt;
* Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.&lt;br /&gt;
* Modifiability: programmers can easily make minor changes in the data representation or operations in an OOP. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.&lt;br /&gt;
* Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.&lt;br /&gt;
* Maintainability: objects can be maintained separately, making locating and fixing problems easier.&lt;br /&gt;
* Re-usability: objects can be reused in different programs.&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
In object-oriented world, data and operations are grouped together into modular units called objects and we combine objects into structured networks to form a program. The results are depend on arguments and objects' state at method invocation time. While in functional world, the basic elements are variables in the mathematical sense and functions in the mathematical sense. Functional programming can reduce side-effects. If there is no side-effects, it means your can apply the function at anywhere freely. No matter how you apply this function, the same input arguments produce the same results.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Functional - Mathematical Functions&lt;br /&gt;
!  Object-Oriented - Objects&lt;br /&gt;
|-&lt;br /&gt;
| Compact&lt;br /&gt;
| Modular&lt;br /&gt;
|-&lt;br /&gt;
| Easy to debug&lt;br /&gt;
| Easy to maintain&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Overall, object-oriented programming requires more upfront design, but is easier to maintain long-term. Obviously if we apply functional programming techniques to object-oriented programming, everything can be done better--the code is easier to write, runs faster, and uses less memory.&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
According to above-mentioned information, we can perform functional programming on an object-oriented programming language because:&lt;br /&gt;
1). object can have constant state &lt;br /&gt;
2). method can depend only on its arguments and context available at method definition time&lt;br /&gt;
&lt;br /&gt;
Combining both these paradigms not only provide us a robust design structure, but also enable the programmers to develop solutions to complex problems quickly and effectively. One of the cornerstone of mixing functional and object-oriented code is treating functions as objects.It means that we can pass functions as arguments, store it and return them from other functions. This is highly useful in an user interface code where it can be used as call back functions which gets called when an event occurs(event driven programming).&lt;br /&gt;
&lt;br /&gt;
Some of the basic features of Functional Programming which can be combined with Object Oriented paradigm are:&lt;br /&gt;
&lt;br /&gt;
* Lambda Calculus&lt;br /&gt;
* Currying&lt;br /&gt;
* Powerful pattern matching&lt;br /&gt;
&lt;br /&gt;
Let us now understand how each of the above feature of Functional language fits in the Object Oriented paradigm.&lt;br /&gt;
&lt;br /&gt;
=== Lambda Calculus ===&lt;br /&gt;
Lambda calculus is the most critical basis of functional programming. A lambda expression is an anonymous expression that contain expressions and statements.Each expression stands for a function with one parameter. &lt;br /&gt;
&lt;br /&gt;
Let consider the following function:&lt;br /&gt;
&lt;br /&gt;
  def f(x)&lt;br /&gt;
  return x**2 &lt;br /&gt;
  print f(4)&lt;br /&gt;
&lt;br /&gt;
We can use a lambda calculus to compute this expression without assigning it to a variable: &lt;br /&gt;
&lt;br /&gt;
  (lambda x:x**x)(4)  &lt;br /&gt;
&lt;br /&gt;
We can see that these two code snippets have the same results. It is more concise and flexible to define with lambda.&lt;br /&gt;
The above is a pure functional approach. In order to make code more state-less and concise, lambdas can be embedded inside the object-oriented language. The below code in Python demonstrates the use of lambda in a closure:&lt;br /&gt;
&lt;br /&gt;
  def fun(x):&lt;br /&gt;
    return x%3==0&lt;br /&gt;
    str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
    filter(fun,str)&lt;br /&gt;
&lt;br /&gt;
The above code works to find numbers which are divisible by 3.&lt;br /&gt;
We can simplify the code by the use of lambda as following:&lt;br /&gt;
&lt;br /&gt;
  str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
  print filter(lambda x: x%3==0, str)&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
In the above information we have learned much about lambda calculus, which take care of one argument, now let me introduce you another concept called currying functions which takes in multiple arguments and returns a chain of functions with lesser number of arguments. It can be interpreted as the technique to decompose a function that takes n parameters into n functions and each of the n functions takes one parameter. &lt;br /&gt;
&lt;br /&gt;
Currying is really an interesting concept. Let's take a sample code in JavaScript to understand it: &lt;br /&gt;
&lt;br /&gt;
  //This is a function for calculating x+y. The difference between this function and general is that this is a currying function.&lt;br /&gt;
  function add(x, y)&lt;br /&gt;
  {&lt;br /&gt;
  if(x!=null &amp;amp;&amp;amp; y!=null) return x + y;&lt;br /&gt;
  else if(x!=null &amp;amp;&amp;amp; y==null) return function(y)&lt;br /&gt;
   { &lt;br /&gt;
     return x + y;  //return a closure with parameter y for subsequent calculations&lt;br /&gt;
    }&lt;br /&gt;
  else if(x==null &amp;amp;&amp;amp; y!=null) return function(x)&lt;br /&gt;
   {&lt;br /&gt;
     return x + y;  //return a closure with parameter x for subsequent calculations&lt;br /&gt;
    }&lt;br /&gt;
   }&lt;br /&gt;
  var a = add(3, 4);  //compute the value of (3+4) and return the value of 7&lt;br /&gt;
  var b = add(2);  //add(2) is equal to a function of (2+y)&lt;br /&gt;
  var c = b(10);  //pass 10 to y, and return the value of (2+10) which is 12&lt;br /&gt;
&lt;br /&gt;
In the above sample, b=add(2) gives us a currying function of add(), which is function of y when x=2.&lt;br /&gt;
&lt;br /&gt;
More interestingly, we can define a currying form of arbitrary functions.&lt;br /&gt;
  function Foo(x, y, z, w)&lt;br /&gt;
  {&lt;br /&gt;
   var args = arguments;&lt;br /&gt;
   if(Foo.length &amp;lt; args.length)&lt;br /&gt;
     return function()&lt;br /&gt;
    {&lt;br /&gt;
      return args.callee.apply(Array.apply([], args).concat(Array.apply([], arguments)));&lt;br /&gt;
    }&lt;br /&gt;
   else&lt;br /&gt;
     return x + y – z * w;&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
What is pattern matching? I think all of you do know what it is, you just don't know you know it. The semantics are equally straightforward.Firstly, we evaluate the value expression, then we walk down the clauses. For each one, we see if the pattern matches the value. If so, we execute the body and end. Simply put, pattern matching is a technique to search string for the occurrence of any patterns or regularity. &lt;br /&gt;
&lt;br /&gt;
Pattern matching allows you to do different calculations according to different identifier values. It looks the same with nests of &amp;quot;if...else&amp;quot; statements, as well as &amp;quot;switch&amp;quot; statements in C++ and C#. But here it is much stronger and more flexible. &lt;br /&gt;
&lt;br /&gt;
You may find that there are two main types of usage of pattern matching:&lt;br /&gt;
* To search and find a particular value.&lt;br /&gt;
* To find a particular value and replace it with selected text. &lt;br /&gt;
&lt;br /&gt;
For example, the following code snippets writes a message if a string contains the text Perl or Python:&lt;br /&gt;
&lt;br /&gt;
  if line =~ /Perl|Python/&lt;br /&gt;
  puts &amp;quot;Scripting language mentioned:#{line}&amp;quot;  &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Next, let us consider the following sample in which a part of a string matched by a regular expression can be replaced with different text using one of Ruby’s substitution methods:&lt;br /&gt;
&lt;br /&gt;
  line.sub(/Perl/, 'Ruby') # replace first 'Perl' with 'Ruby'&lt;br /&gt;
  line.gsub(/Python/, 'Ruby') # replace every 'Python' with 'Ruby'&lt;br /&gt;
&lt;br /&gt;
Advantages of Pattern Matching:&lt;br /&gt;
* It allows concise, readable deconstruction of complex data structures.&lt;br /&gt;
* It gives a possible separation of data structure and respective functionality.&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
A number of programming languages support mixing of both functional and object-oriented code. Three of these (Scala, Ruby, and Conjure), are described in more detail below.&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky. It supports mixing functional and object-oriented code.&lt;br /&gt;
&lt;br /&gt;
==== Mixing Functional and Object-Oriented Code in Scala ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object-oriented and functional programming. How can this happen? The functional world advocates immutability, but the object-oriented world focuses on the state and how to change it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . A rough translation into Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as:&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks much simpler and less verbose. Even though the above example shows an immutable collection, scala also provides mutable collections and object types in the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So it's the best of both worlds. Another part of the functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
==== Implicits in Scala ====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. Since you are splitting open the class and adding/overriding methods (in)|(to) the class, this feature is often called [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching]. Because other libraries may depend on some methods which you changed, often this leads to unexpected behavior at runtime. However, Scala provides yet another feature called [http://en.wikipedia.org/wiki/Implicit_function implicits] which helps you do this better.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Ruby is another language that, like Scala, supports mixing functional and object-oriented code. It is a dynamically typed Object-Oriented Language which supports multiple programming paradigms, including functional, object-oriented, imperative and reflective. In Ruby, everything is an object, every bit of information and code can have its own properties and actions. However, Ruby’s blocks can be functional. A Ruby programmer can attach a closure to any method, which generates a functional block inside an object oriented code. A closure is a piece of code that can access the lexical environment of its definition [http://www.ruby-lang.org/en/ 11].&lt;br /&gt;
&lt;br /&gt;
==== Ruby Mixing Example ====&lt;br /&gt;
&lt;br /&gt;
Consider the following code snippet in Ruby which uses Object Oriented concepts like Classes and functional programming concepts like lambda.&lt;br /&gt;
&lt;br /&gt;
 class Multiply&lt;br /&gt;
   def initialize(n)&lt;br /&gt;
     @block = lambda {|a| n * a}&lt;br /&gt;
   end&lt;br /&gt;
   def mul(a)&lt;br /&gt;
     @block.call a&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 twoMultiplier = Multiply.new 2                     &lt;br /&gt;
 puts twoMultiplier.mul(6)&lt;br /&gt;
&lt;br /&gt;
Here,'''''@block''''' is a closure. When we call the class ''Multiply'' using '''''twoAdder = Multiply.new 2''''' ,the ''initialize'' method is called by passing the parameter 2. Here n=2 binds itself to the block. So @block will be 2*a, that is,the closure remembers the parameter with which the initialize method was called even after the initialize method exits.  &lt;br /&gt;
&lt;br /&gt;
This value is used when the block is called in the add method.  &lt;br /&gt;
Thus,'''''twoMultiplier.mul(6)''''' will return 2*6 = 12&lt;br /&gt;
&lt;br /&gt;
==== Functional Style Coding in Ruby Blocks ====&lt;br /&gt;
&lt;br /&gt;
Blocks are basically nameless functions which can be passed to a function and then that function can invoke the passed in nameless function. This is a common style called [http://en.wikipedia.org/wiki/Higher-order_function higher order functions] among languages that handle functions as first class objects. Basically blocks can be designed for loop abstraction and lets the user to design their own way of iterating the values, thereby hiding the implementation details. &lt;br /&gt;
For example, if we want to iterate backwards from the end to the beginning without revealing its internal implementations, we could implement the loop logic inside the block and pass it to a method or function.&lt;br /&gt;
&lt;br /&gt;
Here is a [http://www.ruby-lang.org/en/ Ruby] implementation of block:&lt;br /&gt;
 &lt;br /&gt;
 def printlist(array,&amp;amp;reverse)&lt;br /&gt;
    array.each do |element|&lt;br /&gt;
       puts &amp;quot;array element: #{element}&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
    reverse.call(array)   /* Here it prints the reverse implementation of list*/&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
 printlist([1,2,3,4,5,6]) { |array| &lt;br /&gt;
   array.reverse.each do |element| &lt;br /&gt;
     puts &amp;quot;array element: #{element}&amp;quot; &lt;br /&gt;
   end &lt;br /&gt;
 }&lt;br /&gt;
The statements between { } is a block and it gets called by &amp;lt;code&amp;gt;reverse.call(array)&amp;lt;/code&amp;gt;within the printlist method.&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 31]] is also a functional programming language, and it is a dialect of Lisp. It is not a pure functional language. Instead, it is a dynamically typed language. Just like Java it runs on JVM platform, but its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
(functions arguments...)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The function and its arguments are enclosed in paranthesis. It has features like immutable data structures, high-order functions, recursion, and easy and fast java interoperability. &lt;br /&gt;
&lt;br /&gt;
In Clojure's model, value calculation is purely functional. Values never change. New values are functions of old. But, logical identity is well supported via atomic references to values. The value of a reference (state of an identity) is always observable without coordination and freely shareable between threads.&lt;br /&gt;
When programs are constructed this way, functional value calculation is independent of identity-value association. This makes clojure easier to understand and test.&lt;br /&gt;
&lt;br /&gt;
====Example Using Functional Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
Consider the following functional programming example in Clojure-&lt;br /&gt;
 (defn make-adder [x]&lt;br /&gt;
   (let [y x]&lt;br /&gt;
     (fn [z] (+ y z))))&lt;br /&gt;
 (def add2 (make-adder 2))&lt;br /&gt;
 (add2 4)&lt;br /&gt;
&lt;br /&gt;
Here,'''''defn make-adder [x]''''' defines a function called ''make-adder''.'''''let [y x]''''' gives a local name y for the value x. Since the scope of any local names is lexical, a function created in the scope of local names will close over their values.'''''fn [z] (+ y z)''''' does the addition of y and z.&lt;br /&gt;
''&lt;br /&gt;
'''def add2 (make-adder 2)''''' calls the function ''make-adder'' passing the parameter 2 and calls this as ''add2''.Now, ''add2'' has computed 2+z. When '''''add2 4''''' is called it computes 2+4=6&lt;br /&gt;
&lt;br /&gt;
====Example Using Object-Oriented Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
The following program implements Run-Time Polymorphism which is an object-oriented programming concept.&lt;br /&gt;
 (defmulti encounter (fn [x y] [(:Species x) (:Species y)]))&lt;br /&gt;
 (defmethod encounter [:Bunny :Lion] [b l] :run-away)&lt;br /&gt;
 (defmethod encounter [:Lion :Bunny] [l b] :eat)&lt;br /&gt;
 (defmethod encounter [:Lion :Lion] [l1 l2] :fight)&lt;br /&gt;
 (defmethod encounter [:Bunny :Bunny] [b1 b2] :mate)&lt;br /&gt;
 (def b1 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def b2 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def l1 {:Species :Lion :other :stuff})&lt;br /&gt;
 (def l2 {:Species :Lion :other :stuff})&lt;br /&gt;
 &lt;br /&gt;
 (encounter b1 l1)&lt;br /&gt;
 -&amp;gt; :run-away&lt;br /&gt;
 (encounter l1 l2)&lt;br /&gt;
 -&amp;gt; :fight&lt;br /&gt;
&lt;br /&gt;
Here,'''''defmulti''''' is used to define multiple methods which have the same method name '''''encounter'''''.Depending on the parameters passed to the encounter method, one of the four methods is called.&lt;br /&gt;
'''''def''''' defines each of the different species.&lt;br /&gt;
When, '''''(encounter b1 l1)''''' is called, the first ''encounter'' method is called with the parameters ''Bunny'' and ''Lion''. As a result, ''run-away'' is printed.&lt;br /&gt;
&lt;br /&gt;
=== Summary of Languages Supporting Mixing ===&lt;br /&gt;
&lt;br /&gt;
Each of the languages contains both functional and object-oriented features. The following table shows how each of the languages have both functional and object-oriented characterics. Not all characteristics of the languages are listed, but enough to demonstrate that the languages each have different ways of mixing object-oriented and functional techniques.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  &lt;br /&gt;
!  Functional Characteristics&lt;br /&gt;
!  Object-Oriented Characteristics&lt;br /&gt;
|-&lt;br /&gt;
! Scala&lt;br /&gt;
| Immutable objects, the ability to pass functions as parameters, implicits, closures.&lt;br /&gt;
| Every value is a object, mutable objects.&lt;br /&gt;
|-&lt;br /&gt;
! Ruby&lt;br /&gt;
| Functional programming used in blocks.&lt;br /&gt;
| Everything is an object.&lt;br /&gt;
|-&lt;br /&gt;
! Clojure&lt;br /&gt;
| Immutable data structures, high-order functions, recursion.&lt;br /&gt;
| Objects, runtime polymorphism, [http://en.wikipedia.org/wiki/Multiple_dispatch multimethods.]&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
In summary, functional and object-oriented programming can be successfully mixed in programs. Many functional techniques are useful in object-oriented programs. Functional programming integrated with object oriented style leads to: &lt;br /&gt;
&lt;br /&gt;
*Better understanding of program behavior and easier debugging as a result of immutability features&lt;br /&gt;
*Use of techniques such as blocks and closures to implement object oriented design and reduce repetitive code&lt;br /&gt;
*Lesser complexity and reduction in the number of lines of code &lt;br /&gt;
&lt;br /&gt;
Languages such as Scala, Ruby, and Clojure effectively support mixing these two paradigms, allowing programmers to create cleaner, less buggy object-oriented code.&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
Special thanks to writers of previous wiki pages (see last three references below).&lt;br /&gt;
&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Functional_programming Wikipedia - Functional Programming]&lt;br /&gt;
#[http://www.cs.cornell.edu/riccardo/prog-smlnj/notes-011001.pdf Notes on programming Standard ML of New Jersey]&lt;br /&gt;
#[http://users.dickinson.edu/~braught/courses/cs132f01/classes/code/Factorial.src.html Introduction to Computing - Dickinson College]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Object-oriented_programming Wikipedia - Object Oriented Programming]&lt;br /&gt;
#[http://searchsoa.techtarget.com/sDefinition/0,,sid26_gci212681,00.html  More on Object Oriented Programming]&lt;br /&gt;
#[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas Understanding Ruby Blocks, Procs and Lambdas - Robert Sosinski]&lt;br /&gt;
#[http://www.codingday.com/power-of-functional-programming-its-features-and-its-future/ Power of Functional Programming, its Features and its Future]&lt;br /&gt;
#[http://skillsmatter.com/podcast/open-source-dot-net/mike-wagg-mark-needham-functional-and-oo-approaches-to-c-sharp-programming Mixing Functional and Object Oriented Approaches to Programming in C#]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigm]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Recursion Recursion]&lt;br /&gt;
#[http://www.scala-lang.org/ Scala]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Scala_%28programming_language%29 Scala Wikipedia]&lt;br /&gt;
#[http://clojure.org/ Clojure]&lt;br /&gt;
#[http://www.ruby-lang.org/en/ Ruby]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Standard_ML Standard ML]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Haskell_%28programming_language%29 Haskell]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/ML_%28programming_language%29 ML Family]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/C%2B%2B C++ Programming Language]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Visual_Basic_.NET Visual Basic .Net]&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;br /&gt;
#O'Reilly (2009), &amp;quot;Programming Scala&amp;quot;, ''O'Reilly Media Inc.''.&lt;br /&gt;
#Dave Thomas, Chad Fowler, Andy Hunt (2006) ''Programming Ruby'', The Pragmatic Bookshelf.&lt;br /&gt;
#[http://lamp.epfl.ch/~phaller/doc/haller10-Translucent_functions.pdf Philipp Halle, Lightweight language support for type-based, concurrent event processing, Lausanne, Switzerland, April 2010.]&lt;br /&gt;
#[http://biblion.epfl.ch/EPFL/theses/2007/3899/EPFL_TH3899.pdf Burak Emir, Object-Oriented Pattern Matching, EPFL, October 2007].&lt;br /&gt;
#[http://math.hws.edu/eck/cs124/downloads/OOP2_from_Univ_KwaZulu-Natal.pdf, Object-Oriented Programming,February 2007].&lt;br /&gt;
#[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_1e_az CSC/ECE 517 Fall 2010/ch1 1e az]&lt;br /&gt;
#[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_1e_AE CSC/ECE 517 Fall 2010/ch1 1e AE]&lt;br /&gt;
#[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_1e_bb CSC/ECE 517 Fall 2010/ch1 1e bb]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63721</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63721"/>
		<updated>2012-09-12T19:25:36Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
This wiki page explores the idea of mixing functional and object-oriented code. Mixing different [http://en.wikipedia.org/wiki/Multi-paradigm#Multi-paradigm_programming_language programming paradigms] is called multi-paradigm programming. There are four major paradigms:&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_paradigm Procedural/imperative paradigms]: Assembly, C, C++, Java, C#&lt;br /&gt;
* Object Oriented paradigm : C++, Java, Python, Ruby, Scala, C#&lt;br /&gt;
* Functional Paradigm : Lisp, Haskell, Clojure, Scala, OCaml, Ruby&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logic Paradigm]: Prolog&lt;br /&gt;
&lt;br /&gt;
In this wiki we explain how functional and object-oriented paradigms can be mixed. First, we explain what functional and object-oriented style programming is. Secondly, we will show how to apply functional techniques to object-oriented programming. Lastly, we discuss languages that support mixing functional and object-oriented code.&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and mandates that data is [http://en.wikipedia.org/wiki/Immutable immutable]. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
== Example Contrasting Imperitive and Functional Styles ==&lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily. &lt;br /&gt;
&lt;br /&gt;
== Advantages of Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-oriented Programming =&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm organized around interacting &amp;quot;objects&amp;quot;(usually instances of a class) rather than &amp;quot;actions&amp;quot; and data rather than logic. A basic principle of OOP is that a program consists of a list of subroutines which can perform individually. &lt;br /&gt;
&lt;br /&gt;
An object-oriented programming language provides support for the following object-oriented concepts--object, class, interface and inheritance. To illustrate this idea clearly and vividly let's review the following example-- your limbs. The &amp;quot;Limbs&amp;quot; is a class. Your body has two objects of type &amp;quot;limbs&amp;quot;, named arms and legs. Their main functions are controlled/ managed by a set of biological signals sent from central nervous system( through an interface). So the nervous system is an interface which your body uses to interact with your limbs. The &amp;quot;limbs&amp;quot; is a well architected class. The &amp;quot;legs&amp;quot; has a subclass which contains &amp;quot;left leg&amp;quot; and &amp;quot;Right leg&amp;quot;. The &amp;quot;legs&amp;quot; is being re-used to create the left leg and right leg by slightly changing the properties of it. If the &amp;quot;legs&amp;quot; owns attributes like length, color of skin etc, then the subclass, which contains &amp;quot;left leg&amp;quot; and &amp;quot;right leg&amp;quot; in this case, automatically inherit these attributes( that is called inheritance).&lt;br /&gt;
&lt;br /&gt;
We could code in object-oriented paradigm as:&lt;br /&gt;
&lt;br /&gt;
  class Limbs  &lt;br /&gt;
  #define a class of limbs&lt;br /&gt;
    def initialize(limbs,length,colorofskin)&lt;br /&gt;
    @limbs=limbs&lt;br /&gt;
    @length=length&lt;br /&gt;
    @colorofskin=colorofskin&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  limbs=Limbs.new(&amp;quot;legs&amp;quot;,&amp;quot;100cm&amp;quot;,&amp;quot;white&amp;quot;)  &lt;br /&gt;
  #create a new object in class &amp;quot;Limbs&amp;quot;&lt;br /&gt;
  class Legs&amp;lt;Limbs   &lt;br /&gt;
  #create a subclass &amp;quot;Legs&amp;quot;,which belong to class&amp;quot;Limbs&amp;quot;&lt;br /&gt;
    def initialize(legs,length,colorofskin)&lt;br /&gt;
      super(length,colorofskin)&lt;br /&gt;
      @legs=legs&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
  legs=legs.new(&amp;quot;left leg&amp;quot;) &lt;br /&gt;
  #create a new object in class of &amp;quot;Legs&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Features of Object-oriented Programming ==&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]. A programmer can simply create a new object that inherits many of its features from super-class. And also, they can overwrite existing operations or add new ones.This makes object-oriented programs easier to modify.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation].This refers to hiding the internal representation of the object from the outside view. You can hide unnecessary implementation details from the object user. One of the benefits of encapsulation is data protection.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism].This allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Consider the operator '+', for numbers it will generate the sum, but for strings it will produce a third string which concatenates the input strings.&lt;br /&gt;
&lt;br /&gt;
== Advantages of Object-oriented Programming ==&lt;br /&gt;
* Simplicity: we use software objects to simulate real world objects, so the complexity is reduced and the program structure is very clear.&lt;br /&gt;
* Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.&lt;br /&gt;
* Modifiability: programmers can easily make minor changes in the data representation or operations in an OOP. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.&lt;br /&gt;
* Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.&lt;br /&gt;
* Maintainability: objects can be maintained separately, making locating and fixing problems easier.&lt;br /&gt;
* Re-usability: objects can be reused in different programs.&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
In object-oriented world, data and operations are grouped together into modular units called objects and we combine objects into structured networks to form a program. The results are depend on arguments and objects' state at method invocation time. While in functional world, the basic elements are variables in the mathematical sense and functions in the mathematical sense. Functional programming can reduce side-effects. If there is no side-effects, it means your can apply the function at anywhere freely. No matter how you apply this function, the same input arguments produce the same results.&lt;br /&gt;
&lt;br /&gt;
Obviously if we apply functional programming techniques to object-oriented programming, everything can be done better--the code is easier to write, runs faster, and uses less memory.&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
According to above-mentioned information, we can perform functional programming on an object-oriented programming language because:&lt;br /&gt;
1). object can have constant state &lt;br /&gt;
2). method can depend only on its arguments and context available at method definition time&lt;br /&gt;
&lt;br /&gt;
Combining both these paradigms not only provide us a robust design structure, but also enable the programmers to develop solutions to complex problems quickly and effectively. One of the cornerstone of mixing functional and object-oriented code is treating functions as objects.It means that we can pass functions as arguments, store it and return them from other functions. This is highly useful in an user interface code where it can be used as call back functions which gets called when an event occurs(event driven programming).&lt;br /&gt;
&lt;br /&gt;
Some of the basic features of Functional Programming which can be combined with Object Oriented paradigm are:&lt;br /&gt;
&lt;br /&gt;
* Lambda Calculus&lt;br /&gt;
* Currying&lt;br /&gt;
* Powerful pattern matching&lt;br /&gt;
&lt;br /&gt;
Let us now understand how each of the above feature of Functional language fits in the Object Oriented paradigm.&lt;br /&gt;
&lt;br /&gt;
=== Lambda Calculus ===&lt;br /&gt;
Lambda calculus is the most critical basis of functional programming. A lambda expression is an anonymous expression that contain expressions and statements.Each expression stands for a function with one parameter. &lt;br /&gt;
&lt;br /&gt;
Let consider the following function:&lt;br /&gt;
&lt;br /&gt;
  def f(x)&lt;br /&gt;
  return x**2 &lt;br /&gt;
  print f(4)&lt;br /&gt;
&lt;br /&gt;
We can use a lambda calculus to compute this expression without assigning it to a variable: &lt;br /&gt;
&lt;br /&gt;
  (lambda x:x**x)(4)  &lt;br /&gt;
&lt;br /&gt;
We can see that these two code snippets have the same results. It is more concise and flexible to define with lambda.&lt;br /&gt;
The above is a pure functional approach. In order to make code more state-less and concise, lambdas can be embedded inside the object-oriented language. The below code in Python demonstrates the use of lambda in a closure:&lt;br /&gt;
&lt;br /&gt;
  def fun(x):&lt;br /&gt;
    return x%3==0&lt;br /&gt;
    str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
    filter(fun,str)&lt;br /&gt;
&lt;br /&gt;
The above code works to find numbers which are divisible by 3.&lt;br /&gt;
We can simplify the code by the use of lambda as following:&lt;br /&gt;
&lt;br /&gt;
  str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
  print filter(lambda x: x%3==0, str)&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
In the above information we have learned much about lambda calculus, which take care of one argument, now let me introduce you another concept called currying functions which takes in multiple arguments and returns a chain of functions with lesser number of arguments. It can be interpreted as the technique to decompose a function that takes n parameters into n functions and each of the n functions takes one parameter. &lt;br /&gt;
&lt;br /&gt;
Currying is really an interesting concept. Let's take a sample code in JavaScript to understand it: &lt;br /&gt;
&lt;br /&gt;
  //This is a function for calculating x+y. The difference between this function and general is that this is a currying function.&lt;br /&gt;
  function add(x, y)&lt;br /&gt;
  {&lt;br /&gt;
  if(x!=null &amp;amp;&amp;amp; y!=null) return x + y;&lt;br /&gt;
  else if(x!=null &amp;amp;&amp;amp; y==null) return function(y)&lt;br /&gt;
   { &lt;br /&gt;
     return x + y;  //return a closure with parameter y for subsequent calculations&lt;br /&gt;
    }&lt;br /&gt;
  else if(x==null &amp;amp;&amp;amp; y!=null) return function(x)&lt;br /&gt;
   {&lt;br /&gt;
     return x + y;  //return a closure with parameter x for subsequent calculations&lt;br /&gt;
    }&lt;br /&gt;
   }&lt;br /&gt;
  var a = add(3, 4);  //compute the value of (3+4) and return the value of 7&lt;br /&gt;
  var b = add(2);  //add(2) is equal to a function of (2+y)&lt;br /&gt;
  var c = b(10);  //pass 10 to y, and return the value of (2+10) which is 12&lt;br /&gt;
&lt;br /&gt;
In the above sample, b=add(2) gives us a currying function of add(), which is function of y when x=2.&lt;br /&gt;
&lt;br /&gt;
More interestingly, we can define a currying form of arbitrary functions.&lt;br /&gt;
  function Foo(x, y, z, w)&lt;br /&gt;
  {&lt;br /&gt;
   var args = arguments;&lt;br /&gt;
   if(Foo.length &amp;lt; args.length)&lt;br /&gt;
     return function()&lt;br /&gt;
    {&lt;br /&gt;
      return args.callee.apply(Array.apply([], args).concat(Array.apply([], arguments)));&lt;br /&gt;
    }&lt;br /&gt;
   else&lt;br /&gt;
     return x + y – z * w;&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
What is pattern matching? I think all of you do know what it is, you just don't know you know it. The semantics are equally straightforward.Firstly, we evaluate the value expression, then we walk down the clauses. For each one, we see if the pattern matches the value. If so, we execute the body and end. Simply put, pattern matching is a technique to search string for the occurrence of any patterns or regularity. &lt;br /&gt;
&lt;br /&gt;
Pattern matching allows you to do different calculations according to different identifier values. It looks the same with nests of &amp;quot;if...else&amp;quot; statements, as well as &amp;quot;switch&amp;quot; statements in C++ and C#. But here it is much stronger and more flexible. &lt;br /&gt;
&lt;br /&gt;
You may find that there are two main types of usage of pattern matching:&lt;br /&gt;
* To search and find a particular value.&lt;br /&gt;
* To find a particular value and replace it with selected text. &lt;br /&gt;
&lt;br /&gt;
For example, the following code snippets writes a message if a string contains the text Perl or Python:&lt;br /&gt;
&lt;br /&gt;
  if line =~ /Perl|Python/&lt;br /&gt;
  puts &amp;quot;Scripting language mentioned:#{line}&amp;quot;  &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Next, let us consider the following sample in which a part of a string matched by a regular expression can be replaced with different text using one of Ruby’s substitution methods:&lt;br /&gt;
&lt;br /&gt;
  line.sub(/Perl/, 'Ruby') # replace first 'Perl' with 'Ruby'&lt;br /&gt;
  line.gsub(/Python/, 'Ruby') # replace every 'Python' with 'Ruby'&lt;br /&gt;
&lt;br /&gt;
Advantages of Pattern Matching:&lt;br /&gt;
* It allows concise, readable deconstruction of complex data structures.&lt;br /&gt;
* It gives a possible separation of data structure and respective functionality.&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
A number of programming languages support mixing of both functional and object-oriented code. Three of these (Scala, Ruby, and Conjure), are described in more detail below.&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky. It supports mixing functional and object-oriented code.&lt;br /&gt;
&lt;br /&gt;
==== Mixing Functional and Object-Oriented Code in Scala ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object-oriented and functional programming. How can this happen? The functional world advocates immutability, but the object-oriented world focuses on the state and how to change it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . A rough translation into Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as:&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks much simpler and less verbose. Even though the above example shows an immutable collection, scala also provides mutable collections and object types in the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So it's the best of both worlds. Another part of the functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
==== Implicits in Scala ====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. Since you are splitting open the class and adding/overriding methods (in)|(to) the class, this feature is often called [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching]. Because other libraries may depend on some methods which you changed, often this leads to unexpected behavior at runtime. However, Scala provides yet another feature called [http://en.wikipedia.org/wiki/Implicit_function implicits] which helps you do this better.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Ruby is another language that, like Scala, supports mixing functional and object-oriented code. It is a dynamically typed Object-Oriented Language which supports multiple programming paradigms, including functional, object-oriented, imperative and reflective. In Ruby, everything is an object, every bit of information and code can have its own properties and actions. However, Ruby’s blocks can be functional. A Ruby programmer can attach a closure to any method, which generates a functional block inside an object oriented code. A closure is a piece of code that can access the lexical environment of its definition [http://www.ruby-lang.org/en/ 11].&lt;br /&gt;
&lt;br /&gt;
==== Ruby Mixing Example ====&lt;br /&gt;
&lt;br /&gt;
Consider the following code snippet in Ruby which uses Object Oriented concepts like Classes and functional programming concepts like lambda.&lt;br /&gt;
&lt;br /&gt;
 class Multiply&lt;br /&gt;
   def initialize(n)&lt;br /&gt;
     @block = lambda {|a| n * a}&lt;br /&gt;
   end&lt;br /&gt;
   def mul(a)&lt;br /&gt;
     @block.call a&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 twoMultiplier = Multiply.new 2                     &lt;br /&gt;
 puts twoMultiplier.mul(6)&lt;br /&gt;
&lt;br /&gt;
Here,'''''@block''''' is a closure. When we call the class ''Multiply'' using '''''twoAdder = Multiply.new 2''''' ,the ''initialize'' method is called by passing the parameter 2. Here n=2 binds itself to the block. So @block will be 2*a, that is,the closure remembers the parameter with which the initialize method was called even after the initialize method exits.  &lt;br /&gt;
&lt;br /&gt;
This value is used when the block is called in the add method.  &lt;br /&gt;
Thus,'''''twoMultiplier.mul(6)''''' will return 2*6 = 12&lt;br /&gt;
&lt;br /&gt;
==== Functional Style Coding in Ruby Blocks ====&lt;br /&gt;
&lt;br /&gt;
Blocks are basically nameless functions which can be passed to a function and then that function can invoke the passed in nameless function. This is a common style called [http://en.wikipedia.org/wiki/Higher-order_function higher order functions] among languages that handle functions as first class objects. Basically blocks can be designed for loop abstraction and lets the user to design their own way of iterating the values, thereby hiding the implementation details. &lt;br /&gt;
For example, if we want to iterate backwards from the end to the beginning without revealing its internal implementations, we could implement the loop logic inside the block and pass it to a method or function.&lt;br /&gt;
&lt;br /&gt;
Here is a [http://www.ruby-lang.org/en/ Ruby] implementation of block:&lt;br /&gt;
 &lt;br /&gt;
 def printlist(array,&amp;amp;reverse)&lt;br /&gt;
    array.each do |element|&lt;br /&gt;
       puts &amp;quot;array element: #{element}&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
    reverse.call(array)   /* Here it prints the reverse implementation of list*/&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
 printlist([1,2,3,4,5,6]) { |array| &lt;br /&gt;
   array.reverse.each do |element| &lt;br /&gt;
     puts &amp;quot;array element: #{element}&amp;quot; &lt;br /&gt;
   end &lt;br /&gt;
 }&lt;br /&gt;
The statements between { } is a block and it gets called by &amp;lt;code&amp;gt;reverse.call(array)&amp;lt;/code&amp;gt;within the printlist method.&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 31]] is also a functional programming language, and it is a dialect of Lisp. It is not a pure functional language. Instead, it is a dynamically typed language. Just like Java it runs on JVM platform, but its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
(functions arguments...)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The function and its arguments are enclosed in paranthesis. It has features like immutable data structures, high-order functions, recursion, and easy and fast java interoperability. &lt;br /&gt;
&lt;br /&gt;
In Clojure's model, value calculation is purely functional. Values never change. New values are functions of old. But, logical identity is well supported via atomic references to values. The value of a reference (state of an identity) is always observable without coordination and freely shareable between threads.&lt;br /&gt;
When programs are constructed this way, functional value calculation is independent of identity-value association. This makes clojure easier to understand and test.&lt;br /&gt;
&lt;br /&gt;
====Example Using Functional Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
Consider the following functional programming example in Clojure-&lt;br /&gt;
 (defn make-adder [x]&lt;br /&gt;
   (let [y x]&lt;br /&gt;
     (fn [z] (+ y z))))&lt;br /&gt;
 (def add2 (make-adder 2))&lt;br /&gt;
 (add2 4)&lt;br /&gt;
&lt;br /&gt;
Here,'''''defn make-adder [x]''''' defines a function called ''make-adder''.'''''let [y x]''''' gives a local name y for the value x. Since the scope of any local names is lexical, a function created in the scope of local names will close over their values.'''''fn [z] (+ y z)''''' does the addition of y and z.&lt;br /&gt;
''&lt;br /&gt;
'''def add2 (make-adder 2)''''' calls the function ''make-adder'' passing the parameter 2 and calls this as ''add2''.Now, ''add2'' has computed 2+z. When '''''add2 4''''' is called it computes 2+4=6&lt;br /&gt;
&lt;br /&gt;
====Example Using Object-Oriented Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
The following program implements Run-Time Polymorphism which is an object-oriented programming concept.&lt;br /&gt;
 (defmulti encounter (fn [x y] [(:Species x) (:Species y)]))&lt;br /&gt;
 (defmethod encounter [:Bunny :Lion] [b l] :run-away)&lt;br /&gt;
 (defmethod encounter [:Lion :Bunny] [l b] :eat)&lt;br /&gt;
 (defmethod encounter [:Lion :Lion] [l1 l2] :fight)&lt;br /&gt;
 (defmethod encounter [:Bunny :Bunny] [b1 b2] :mate)&lt;br /&gt;
 (def b1 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def b2 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def l1 {:Species :Lion :other :stuff})&lt;br /&gt;
 (def l2 {:Species :Lion :other :stuff})&lt;br /&gt;
 &lt;br /&gt;
 (encounter b1 l1)&lt;br /&gt;
 -&amp;gt; :run-away&lt;br /&gt;
 (encounter l1 l2)&lt;br /&gt;
 -&amp;gt; :fight&lt;br /&gt;
&lt;br /&gt;
Here,'''''defmulti''''' is used to define multiple methods which have the same method name '''''encounter'''''.Depending on the parameters passed to the encounter method, one of the four methods is called.&lt;br /&gt;
'''''def''''' defines each of the different species.&lt;br /&gt;
When, '''''(encounter b1 l1)''''' is called, the first ''encounter'' method is called with the parameters ''Bunny'' and ''Lion''. As a result, ''run-away'' is printed.&lt;br /&gt;
&lt;br /&gt;
=== Summary of Languages Supporting Mixing ===&lt;br /&gt;
&lt;br /&gt;
Each of the languages contains both functional and object-oriented features. The following table shows how each of the languages have both functional and object-oriented characterics. Not all characteristics of the languages are listed, but enough to demonstrate that the languages each have different ways of mixing object-oriented and functional techniques.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  &lt;br /&gt;
!  Functional Characteristics&lt;br /&gt;
!  Object-Oriented Characteristics&lt;br /&gt;
|-&lt;br /&gt;
! Scala&lt;br /&gt;
| Immutable objects, the ability to pass functions as parameters, implicits, closures.&lt;br /&gt;
| Every value is a object, mutable objects.&lt;br /&gt;
|-&lt;br /&gt;
! Ruby&lt;br /&gt;
| Functional programming used in blocks.&lt;br /&gt;
| Everything is an object.&lt;br /&gt;
|-&lt;br /&gt;
! Clojure&lt;br /&gt;
| Immutable data structures, high-order functions, recursion.&lt;br /&gt;
| Objects, runtime polymorphism, [http://en.wikipedia.org/wiki/Multiple_dispatch multimethods.]&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
In summary, functional and object-oriented programming can be successfully mixed in programs. Many functional techniques are useful in object-oriented programs. Functional programming integrated with object oriented style leads to: &lt;br /&gt;
&lt;br /&gt;
*Better understanding of program behavior and easier debugging as a result of immutability features&lt;br /&gt;
*Use of techniques such as blocks and closures to implement object oriented design and reduce repetitive code&lt;br /&gt;
*Lesser complexity and reduction in the number of lines of code &lt;br /&gt;
&lt;br /&gt;
Languages such as Scala, Ruby, and Clojure effectively support mixing these two paradigms, allowing programmers to create cleaner, less buggy object-oriented code.&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
Special thanks to writers of previous wiki pages (see last three references below).&lt;br /&gt;
&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Functional_programming Wikipedia - Functional Programming]&lt;br /&gt;
#[http://www.cs.cornell.edu/riccardo/prog-smlnj/notes-011001.pdf Notes on programming Standard ML of New Jersey]&lt;br /&gt;
#[http://users.dickinson.edu/~braught/courses/cs132f01/classes/code/Factorial.src.html Introduction to Computing - Dickinson College]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Object-oriented_programming Wikipedia - Object Oriented Programming]&lt;br /&gt;
#[http://searchsoa.techtarget.com/sDefinition/0,,sid26_gci212681,00.html  More on Object Oriented Programming]&lt;br /&gt;
#[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas Understanding Ruby Blocks, Procs and Lambdas - Robert Sosinski]&lt;br /&gt;
#[http://www.codingday.com/power-of-functional-programming-its-features-and-its-future/ Power of Functional Programming, its Features and its Future]&lt;br /&gt;
#[http://skillsmatter.com/podcast/open-source-dot-net/mike-wagg-mark-needham-functional-and-oo-approaches-to-c-sharp-programming Mixing Functional and Object Oriented Approaches to Programming in C#]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigm]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Recursion Recursion]&lt;br /&gt;
#[http://www.scala-lang.org/ Scala]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Scala_%28programming_language%29 Scala Wikipedia]&lt;br /&gt;
#[http://clojure.org/ Clojure]&lt;br /&gt;
#[http://www.ruby-lang.org/en/ Ruby]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Standard_ML Standard ML]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Haskell_%28programming_language%29 Haskell]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/ML_%28programming_language%29 ML Family]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/C%2B%2B C++ Programming Language]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Visual_Basic_.NET Visual Basic .Net]&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;br /&gt;
#O'Reilly (2009), &amp;quot;Programming Scala&amp;quot;, ''O'Reilly Media Inc.''.&lt;br /&gt;
#Dave Thomas, Chad Fowler, Andy Hunt (2006) ''Programming Ruby'', The Pragmatic Bookshelf.&lt;br /&gt;
#[http://lamp.epfl.ch/~phaller/doc/haller10-Translucent_functions.pdf Philipp Halle, Lightweight language support for type-based, concurrent event processing, Lausanne, Switzerland, April 2010.]&lt;br /&gt;
#[http://biblion.epfl.ch/EPFL/theses/2007/3899/EPFL_TH3899.pdf Burak Emir, Object-Oriented Pattern Matching, EPFL, October 2007].&lt;br /&gt;
#[http://math.hws.edu/eck/cs124/downloads/OOP2_from_Univ_KwaZulu-Natal.pdf, Object-Oriented Programming,February 2007].&lt;br /&gt;
#[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_1e_az CSC/ECE 517 Fall 2010/ch1 1e az]&lt;br /&gt;
#[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_1e_AE CSC/ECE 517 Fall 2010/ch1 1e AE]&lt;br /&gt;
#[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_1e_bb CSC/ECE 517 Fall 2010/ch1 1e bb]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63720</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63720"/>
		<updated>2012-09-12T19:18:04Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Conclusion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
This wiki page explores the idea of mixing functional and object-oriented code. Mixing different [http://en.wikipedia.org/wiki/Multi-paradigm#Multi-paradigm_programming_language programming paradigms] is called multi-paradigm programming. There are four major paradigms:&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_paradigm Procedural/imperative paradigms]: Assembly, C, C++, Java, C#&lt;br /&gt;
* Object Oriented paradigm : C++, Java, Python, Ruby, Scala, C#&lt;br /&gt;
* Functional Paradigm : Lisp, Haskell, Clojure, Scala, OCaml, Ruby&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logic Paradigm]: Prolog&lt;br /&gt;
&lt;br /&gt;
In this wiki we explain how functional and object-oriented paradigms can be mixed. First, we explain what functional and object-oriented style programming is. Secondly, we will show how to apply functional techniques to object-oriented programming. Lastly, we discuss languages that support mixing functional and object-oriented code.&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and mandates that data is [http://en.wikipedia.org/wiki/Immutable immutable]. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
== Example Contrasting Imperitive and Functional Styles ==&lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily. &lt;br /&gt;
&lt;br /&gt;
== Advantages of Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-oriented Programming =&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm organized around interacting &amp;quot;objects&amp;quot;(usually instances of a class) rather than &amp;quot;actions&amp;quot; and data rather than logic. A basic principle of OOP is that a program consists of a list of subroutines which can perform individually. &lt;br /&gt;
&lt;br /&gt;
An object-oriented programming language provides support for the following object-oriented concepts--object, class, interface and inheritance. To illustrate this idea clearly and vividly let's review the following example-- your limbs. The &amp;quot;Limbs&amp;quot; is a class. Your body has two objects of type &amp;quot;limbs&amp;quot;, named arms and legs. Their main functions are controlled/ managed by a set of biological signals sent from central nervous system( through an interface). So the nervous system is an interface which your body uses to interact with your limbs. The &amp;quot;limbs&amp;quot; is a well architected class. The &amp;quot;legs&amp;quot; has a subclass which contains &amp;quot;left leg&amp;quot; and &amp;quot;Right leg&amp;quot;. The &amp;quot;legs&amp;quot; is being re-used to create the left leg and right leg by slightly changing the properties of it. If the &amp;quot;legs&amp;quot; owns attributes like length, color of skin etc, then the subclass, which contains &amp;quot;left leg&amp;quot; and &amp;quot;right leg&amp;quot; in this case, automatically inherit these attributes( that is called inheritance).&lt;br /&gt;
&lt;br /&gt;
We could code in object-oriented paradigm as:&lt;br /&gt;
&lt;br /&gt;
  class Limbs  &lt;br /&gt;
  #define a class of limbs&lt;br /&gt;
    def initialize(limbs,length,colorofskin)&lt;br /&gt;
    @limbs=limbs&lt;br /&gt;
    @length=length&lt;br /&gt;
    @colorofskin=colorofskin&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  limbs=Limbs.new(&amp;quot;legs&amp;quot;,&amp;quot;100cm&amp;quot;,&amp;quot;white&amp;quot;)  &lt;br /&gt;
  #create a new object in class &amp;quot;Limbs&amp;quot;&lt;br /&gt;
  class Legs&amp;lt;Limbs   &lt;br /&gt;
  #create a subclass &amp;quot;Legs&amp;quot;,which belong to class&amp;quot;Limbs&amp;quot;&lt;br /&gt;
    def initialize(legs,length,colorofskin)&lt;br /&gt;
      super(length,colorofskin)&lt;br /&gt;
      @legs=legs&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
  legs=legs.new(&amp;quot;left leg&amp;quot;) &lt;br /&gt;
  #create a new object in class of &amp;quot;Legs&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Features of Object-oriented Programming ==&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]. A programmer can simply create a new object that inherits many of its features from super-class. And also, they can overwrite existing operations or add new ones.This makes object-oriented programs easier to modify.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation].This refers to hiding the internal representation of the object from the outside view. You can hide unnecessary implementation details from the object user. One of the benefits of encapsulation is data protection.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism].This allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Consider the operator '+', for numbers it will generate the sum, but for strings it will produce a third string which concatenates the input strings.&lt;br /&gt;
&lt;br /&gt;
== Advantages of Object-oriented Programming ==&lt;br /&gt;
* Simplicity: we use software objects to simulate real world objects, so the complexity is reduced and the program structure is very clear.&lt;br /&gt;
* Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.&lt;br /&gt;
* Modifiability: programmers can easily make minor changes in the data representation or operations in an OOP. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.&lt;br /&gt;
* Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.&lt;br /&gt;
* Maintainability: objects can be maintained separately, making locating and fixing problems easier.&lt;br /&gt;
* Re-usability: objects can be reused in different programs.&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
In object-oriented world, data and operations are grouped together into modular units called objects and we combine objects into structured networks to form a program. The results are depend on arguments and objects' state at method invocation time. While in functional world, the basic elements are variables in the mathematical sense and functions in the mathematical sense. Functional programming can reduce side-effects. If there is no side-effects, it means your can apply the function at anywhere freely. No matter how you apply this function, the same input arguments produce the same results.&lt;br /&gt;
&lt;br /&gt;
Obviously if we apply functional programming techniques to object-oriented programming, everything can be done better--the code is easier to write, runs faster, and uses less memory.&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
According to above-mentioned information, we can perform functional programming on an object-oriented programming language because:&lt;br /&gt;
1). object can have constant state &lt;br /&gt;
2). method can depend only on its arguments and context available at method definition time&lt;br /&gt;
&lt;br /&gt;
Combining both these paradigms not only provide us a robust design structure, but also enable the programmers to develop solutions to complex problems quickly and effectively. One of the cornerstone of mixing functional and object-oriented code is treating functions as objects.It means that we can pass functions as arguments, store it and return them from other functions. This is highly useful in an user interface code where it can be used as call back functions which gets called when an event occurs(event driven programming).&lt;br /&gt;
&lt;br /&gt;
Some of the basic features of Functional Programming which can be combined with Object Oriented paradigm are:&lt;br /&gt;
&lt;br /&gt;
* Lambda Calculus&lt;br /&gt;
* Currying&lt;br /&gt;
* Powerful pattern matching&lt;br /&gt;
&lt;br /&gt;
Let us now understand how each of the above feature of Functional language fits in the Object Oriented paradigm.&lt;br /&gt;
&lt;br /&gt;
=== Lambda Calculus ===&lt;br /&gt;
Lambda calculus is the most critical basis of functional programming. A lambda expression is an anonymous expression that contain expressions and statements.Each expression stands for a function with one parameter. &lt;br /&gt;
&lt;br /&gt;
Let consider the following function:&lt;br /&gt;
&lt;br /&gt;
  def f(x)&lt;br /&gt;
  return x**2 &lt;br /&gt;
  print f(4)&lt;br /&gt;
&lt;br /&gt;
We can use a lambda calculus to compute this expression without assigning it to a variable: &lt;br /&gt;
&lt;br /&gt;
  (lambda x:x**x)(4)  &lt;br /&gt;
&lt;br /&gt;
We can see that these two code snippets have the same results. It is more concise and flexible to define with lambda.&lt;br /&gt;
The above is a pure functional approach. In order to make code more state-less and concise, lambdas can be embedded inside the object-oriented language. The below code in Python demonstrates the use of lambda in a closure:&lt;br /&gt;
&lt;br /&gt;
  def fun(x):&lt;br /&gt;
    return x%3==0&lt;br /&gt;
    str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
    filter(fun,str)&lt;br /&gt;
&lt;br /&gt;
The above code works to find numbers which are divisible by 3.&lt;br /&gt;
We can simplify the code by the use of lambda as following:&lt;br /&gt;
&lt;br /&gt;
  str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
  print filter(lambda x: x%3==0, str)&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
In the above information we have learned much about lambda calculus, which take care of one argument, now let me introduce you another concept called currying functions which takes in multiple arguments and returns a chain of functions with lesser number of arguments. It can be interpreted as the technique to decompose a function that takes n parameters into n functions and each of the n functions takes one parameter. &lt;br /&gt;
&lt;br /&gt;
Currying is really an interesting concept. Let's take a sample code in JavaScript to understand it: &lt;br /&gt;
&lt;br /&gt;
  //This is a function for calculating x+y. The difference between this function and general is that this is a currying function.&lt;br /&gt;
  function add(x, y)&lt;br /&gt;
  {&lt;br /&gt;
  if(x!=null &amp;amp;&amp;amp; y!=null) return x + y;&lt;br /&gt;
  else if(x!=null &amp;amp;&amp;amp; y==null) return function(y)&lt;br /&gt;
   { &lt;br /&gt;
     return x + y;  //return a closure with parameter y for subsequent calculations&lt;br /&gt;
    }&lt;br /&gt;
  else if(x==null &amp;amp;&amp;amp; y!=null) return function(x)&lt;br /&gt;
   {&lt;br /&gt;
     return x + y;  //return a closure with parameter x for subsequent calculations&lt;br /&gt;
    }&lt;br /&gt;
   }&lt;br /&gt;
  var a = add(3, 4);  //compute the value of (3+4) and return the value of 7&lt;br /&gt;
  var b = add(2);  //add(2) is equal to a function of (2+y)&lt;br /&gt;
  var c = b(10);  //pass 10 to y, and return the value of (2+10) which is 12&lt;br /&gt;
&lt;br /&gt;
In the above sample, b=add(2) gives us a currying function of add(), which is function of y when x=2.&lt;br /&gt;
&lt;br /&gt;
More interestingly, we can define a currying form of arbitrary functions.&lt;br /&gt;
  function Foo(x, y, z, w)&lt;br /&gt;
  {&lt;br /&gt;
   var args = arguments;&lt;br /&gt;
   if(Foo.length &amp;lt; args.length)&lt;br /&gt;
     return function()&lt;br /&gt;
    {&lt;br /&gt;
      return args.callee.apply(Array.apply([], args).concat(Array.apply([], arguments)));&lt;br /&gt;
    }&lt;br /&gt;
   else&lt;br /&gt;
     return x + y – z * w;&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
What is pattern matching? I think all of you do know what it is, you just don't know you know it. The semantics are equally straightforward.Firstly, we evaluate the value expression, then we walk down the clauses. For each one, we see if the pattern matches the value. If so, we execute the body and end. Simply put, pattern matching is a technique to search string for the occurrence of any patterns or regularity. &lt;br /&gt;
&lt;br /&gt;
Pattern matching allows you to do different calculations according to different identifier values. It looks the same with nests of &amp;quot;if...else&amp;quot; statements, as well as &amp;quot;switch&amp;quot; statements in C++ and C#. But here it is much stronger and more flexible. &lt;br /&gt;
&lt;br /&gt;
You may find that there are two main types of usage of pattern matching:&lt;br /&gt;
* To search and find a particular value.&lt;br /&gt;
* To find a particular value and replace it with selected text. &lt;br /&gt;
&lt;br /&gt;
For example, the following code snippets writes a message if a string contains the text Perl or Python:&lt;br /&gt;
&lt;br /&gt;
  if line =~ /Perl|Python/&lt;br /&gt;
  puts &amp;quot;Scripting language mentioned:#{line}&amp;quot;  &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Next, let us consider the following sample in which a part of a string matched by a regular expression can be replaced with different text using one of Ruby’s substitution methods:&lt;br /&gt;
&lt;br /&gt;
  line.sub(/Perl/, 'Ruby') # replace first 'Perl' with 'Ruby'&lt;br /&gt;
  line.gsub(/Python/, 'Ruby') # replace every 'Python' with 'Ruby'&lt;br /&gt;
&lt;br /&gt;
Advantages of Pattern Matching:&lt;br /&gt;
* It allows concise, readable deconstruction of complex data structures.&lt;br /&gt;
* It gives a possible separation of data structure and respective functionality.&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
A number of programming languages support mixing of both functional and object-oriented code. Three of these (Scala, Ruby, and Conjure), are described in more detail below.&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky. It supports mixing functional and object-oriented code.&lt;br /&gt;
&lt;br /&gt;
==== Mixing Functional and Object-Oriented Code in Scala ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object-oriented and functional programming. How can this happen? The functional world advocates immutability, but the object-oriented world focuses on the state and how to change it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . A rough translation into Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as:&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks much simpler and less verbose. Even though the above example shows an immutable collection, scala also provides mutable collections and object types in the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So it's the best of both worlds. Another part of the functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
==== Implicits in Scala ====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. Since you are splitting open the class and adding/overriding methods (in)|(to) the class, this feature is often called [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching]. Because other libraries may depend on some methods which you changed, often this leads to unexpected behavior at runtime. However, Scala provides yet another feature called [http://en.wikipedia.org/wiki/Implicit_function implicits] which helps you do this better.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Ruby is another language that, like Scala, supports mixing functional and object-oriented code. It is a dynamically typed Object-Oriented Language which supports multiple programming paradigms, including functional, object-oriented, imperative and reflective. In Ruby, everything is an object, every bit of information and code can have its own properties and actions. However, Ruby’s blocks can be functional. A Ruby programmer can attach a closure to any method, which generates a functional block inside an object oriented code. A closure is a piece of code that can access the lexical environment of its definition [http://www.ruby-lang.org/en/ 11].&lt;br /&gt;
&lt;br /&gt;
==== Ruby Mixing Example ====&lt;br /&gt;
&lt;br /&gt;
Consider the following code snippet in Ruby which uses Object Oriented concepts like Classes and functional programming concepts like lambda.&lt;br /&gt;
&lt;br /&gt;
 class Multiply&lt;br /&gt;
   def initialize(n)&lt;br /&gt;
     @block = lambda {|a| n * a}&lt;br /&gt;
   end&lt;br /&gt;
   def mul(a)&lt;br /&gt;
     @block.call a&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 twoMultiplier = Multiply.new 2                     &lt;br /&gt;
 puts twoMultiplier.mul(6)&lt;br /&gt;
&lt;br /&gt;
Here,'''''@block''''' is a closure. When we call the class ''Multiply'' using '''''twoAdder = Multiply.new 2''''' ,the ''initialize'' method is called by passing the parameter 2. Here n=2 binds itself to the block. So @block will be 2*a, that is,the closure remembers the parameter with which the initialize method was called even after the initialize method exits.  &lt;br /&gt;
&lt;br /&gt;
This value is used when the block is called in the add method.  &lt;br /&gt;
Thus,'''''twoMultiplier.mul(6)''''' will return 2*6 = 12&lt;br /&gt;
&lt;br /&gt;
==== Functional Style Coding in Ruby Blocks ====&lt;br /&gt;
&lt;br /&gt;
Blocks are basically nameless functions which can be passed to a function and then that function can invoke the passed in nameless function. This is a common style called [http://en.wikipedia.org/wiki/Higher-order_function higher order functions] among languages that handle functions as first class objects. Basically blocks can be designed for loop abstraction and lets the user to design their own way of iterating the values, thereby hiding the implementation details. &lt;br /&gt;
For example, if we want to iterate backwards from the end to the beginning without revealing its internal implementations, we could implement the loop logic inside the block and pass it to a method or function.&lt;br /&gt;
&lt;br /&gt;
Here is a [http://www.ruby-lang.org/en/ Ruby] implementation of block:&lt;br /&gt;
 &lt;br /&gt;
 def printlist(array,&amp;amp;reverse)&lt;br /&gt;
    array.each do |element|&lt;br /&gt;
       puts &amp;quot;array element: #{element}&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
    reverse.call(array)   /* Here it prints the reverse implementation of list*/&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
 printlist([1,2,3,4,5,6]) { |array| &lt;br /&gt;
   array.reverse.each do |element| &lt;br /&gt;
     puts &amp;quot;array element: #{element}&amp;quot; &lt;br /&gt;
   end &lt;br /&gt;
 }&lt;br /&gt;
The statements between { } is a block and it gets called by &amp;lt;code&amp;gt;reverse.call(array)&amp;lt;/code&amp;gt;within the printlist method.&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 31]] is also a functional programming language, and it is a dialect of Lisp. It is not a pure functional language. Instead, it is a dynamically typed language. Just like Java it runs on JVM platform, but its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
(functions arguments...)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The function and its arguments are enclosed in paranthesis. It has features like immutable data structures, high-order functions, recursion, and easy and fast java interoperability. &lt;br /&gt;
&lt;br /&gt;
In Clojure's model, value calculation is purely functional. Values never change. New values are functions of old. But, logical identity is well supported via atomic references to values. The value of a reference (state of an identity) is always observable without coordination and freely shareable between threads.&lt;br /&gt;
When programs are constructed this way, functional value calculation is independent of identity-value association. This makes clojure easier to understand and test.&lt;br /&gt;
&lt;br /&gt;
====Example Using Functional Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
Consider the following functional programming example in Clojure-&lt;br /&gt;
 (defn make-adder [x]&lt;br /&gt;
   (let [y x]&lt;br /&gt;
     (fn [z] (+ y z))))&lt;br /&gt;
 (def add2 (make-adder 2))&lt;br /&gt;
 (add2 4)&lt;br /&gt;
&lt;br /&gt;
Here,'''''defn make-adder [x]''''' defines a function called ''make-adder''.'''''let [y x]''''' gives a local name y for the value x. Since the scope of any local names is lexical, a function created in the scope of local names will close over their values.'''''fn [z] (+ y z)''''' does the addition of y and z.&lt;br /&gt;
''&lt;br /&gt;
'''def add2 (make-adder 2)''''' calls the function ''make-adder'' passing the parameter 2 and calls this as ''add2''.Now, ''add2'' has computed 2+z. When '''''add2 4''''' is called it computes 2+4=6&lt;br /&gt;
&lt;br /&gt;
====Example Using Object-Oriented Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
The following program implements Run-Time Polymorphism which is an object-oriented programming concept.&lt;br /&gt;
 (defmulti encounter (fn [x y] [(:Species x) (:Species y)]))&lt;br /&gt;
 (defmethod encounter [:Bunny :Lion] [b l] :run-away)&lt;br /&gt;
 (defmethod encounter [:Lion :Bunny] [l b] :eat)&lt;br /&gt;
 (defmethod encounter [:Lion :Lion] [l1 l2] :fight)&lt;br /&gt;
 (defmethod encounter [:Bunny :Bunny] [b1 b2] :mate)&lt;br /&gt;
 (def b1 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def b2 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def l1 {:Species :Lion :other :stuff})&lt;br /&gt;
 (def l2 {:Species :Lion :other :stuff})&lt;br /&gt;
 &lt;br /&gt;
 (encounter b1 l1)&lt;br /&gt;
 -&amp;gt; :run-away&lt;br /&gt;
 (encounter l1 l2)&lt;br /&gt;
 -&amp;gt; :fight&lt;br /&gt;
&lt;br /&gt;
Here,'''''defmulti''''' is used to define multiple methods which have the same method name '''''encounter'''''.Depending on the parameters passed to the encounter method, one of the four methods is called.&lt;br /&gt;
'''''def''''' defines each of the different species.&lt;br /&gt;
When, '''''(encounter b1 l1)''''' is called, the first ''encounter'' method is called with the parameters ''Bunny'' and ''Lion''. As a result, ''run-away'' is printed.&lt;br /&gt;
&lt;br /&gt;
=== Summary of Languages Supporting Mixing ===&lt;br /&gt;
&lt;br /&gt;
Each of the languages contains both functional and object-oriented features. The following table shows how each of the languages have both functional and object-oriented characterics. Not all characteristics of the languages are listed, but enough to demonstrate that the languages each have different ways of mixing object-oriented and functional techniques.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  &lt;br /&gt;
!  Functional Characteristics&lt;br /&gt;
!  Object-Oriented Characteristics&lt;br /&gt;
|-&lt;br /&gt;
! Scala&lt;br /&gt;
| Immutable objects, the ability to pass functions as parameters, implicits, closures.&lt;br /&gt;
| Every value is a object, mutable objects.&lt;br /&gt;
|-&lt;br /&gt;
! Ruby&lt;br /&gt;
| Functional programming used in blocks.&lt;br /&gt;
| Everything is an object.&lt;br /&gt;
|-&lt;br /&gt;
! Clojure&lt;br /&gt;
| Immutable data structures, high-order functions, recursion.&lt;br /&gt;
| Objects, runtime polymorphism, [http://en.wikipedia.org/wiki/Multiple_dispatch multimethods.]&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
In summary, functional and object-oriented programming can be successfully mixed in programs. Many functional techniques are useful in object-oriented programs. Functional programming integrated with object oriented style leads to: &lt;br /&gt;
&lt;br /&gt;
*Better understanding of program behavior and easier debugging as a result of immutability features&lt;br /&gt;
*Use of techniques such as blocks and closures to implement object oriented design and reduce repetitive code&lt;br /&gt;
*Lesser complexity and reduction in the number of lines of code &lt;br /&gt;
&lt;br /&gt;
Languages such as Scala, Ruby, and Clojure effectively support mixing these two paradigms, allowing programmers to create cleaner, less buggy object-oriented code.&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Functional_programming Wikipedia - Functional Programming]&lt;br /&gt;
#[http://www.cs.cornell.edu/riccardo/prog-smlnj/notes-011001.pdf Notes on programming Standard ML of New Jersey]&lt;br /&gt;
#[http://users.dickinson.edu/~braught/courses/cs132f01/classes/code/Factorial.src.html Introduction to Computing - Dickinson College]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Object-oriented_programming Wikipedia - Object Oriented Programming]&lt;br /&gt;
#[http://searchsoa.techtarget.com/sDefinition/0,,sid26_gci212681,00.html  More on Object Oriented Programming]&lt;br /&gt;
#[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas Understanding Ruby Blocks, Procs and Lambdas - Robert Sosinski]&lt;br /&gt;
#[http://www.codingday.com/power-of-functional-programming-its-features-and-its-future/ Power of Functional Programming, its Features and its Future]&lt;br /&gt;
#[http://skillsmatter.com/podcast/open-source-dot-net/mike-wagg-mark-needham-functional-and-oo-approaches-to-c-sharp-programming Mixing Functional and Object Oriented Approaches to Programming in C#]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigm]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Recursion Recursion]&lt;br /&gt;
#[http://www.scala-lang.org/ Scala]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Scala_%28programming_language%29 Scala Wikipedia]&lt;br /&gt;
#[http://clojure.org/ Clojure]&lt;br /&gt;
#[http://www.ruby-lang.org/en/ Ruby]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Standard_ML Standard ML]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Haskell_%28programming_language%29 Haskell]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/ML_%28programming_language%29 ML Family]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/C%2B%2B C++ Programming Language]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Visual_Basic_.NET Visual Basic .Net]&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;br /&gt;
#O'Reilly (2009), &amp;quot;Programming Scala&amp;quot;, ''O'Reilly Media Inc.''.&lt;br /&gt;
#Dave Thomas, Chad Fowler, Andy Hunt (2006) ''Programming Ruby'', The Pragmatic Bookshelf.&lt;br /&gt;
#[http://lamp.epfl.ch/~phaller/doc/haller10-Translucent_functions.pdf Philipp Halle, Lightweight language support for type-based, concurrent event processing, Lausanne, Switzerland, April 2010.]&lt;br /&gt;
#[http://biblion.epfl.ch/EPFL/theses/2007/3899/EPFL_TH3899.pdf Burak Emir, Object-Oriented Pattern Matching, EPFL, October 2007].&lt;br /&gt;
#[http://math.hws.edu/eck/cs124/downloads/OOP2_from_Univ_KwaZulu-Natal.pdf, Object-Oriented Programming,February 2007].&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63718</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63718"/>
		<updated>2012-09-12T19:12:47Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Conclusion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
This wiki page explores the idea of mixing functional and object-oriented code. Mixing different [http://en.wikipedia.org/wiki/Multi-paradigm#Multi-paradigm_programming_language programming paradigms] is called multi-paradigm programming. There are four major paradigms:&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_paradigm Procedural/imperative paradigms]: Assembly, C, C++, Java, C#&lt;br /&gt;
* Object Oriented paradigm : C++, Java, Python, Ruby, Scala, C#&lt;br /&gt;
* Functional Paradigm : Lisp, Haskell, Clojure, Scala, OCaml, Ruby&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logic Paradigm]: Prolog&lt;br /&gt;
&lt;br /&gt;
In this wiki we explain how functional and object-oriented paradigms can be mixed. First, we explain what functional and object-oriented style programming is. Secondly, we will show how to apply functional techniques to object-oriented programming. Lastly, we discuss languages that support mixing functional and object-oriented code.&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and mandates that data is [http://en.wikipedia.org/wiki/Immutable immutable]. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
== Example Contrasting Imperitive and Functional Styles ==&lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily. &lt;br /&gt;
&lt;br /&gt;
== Advantages of Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-oriented Programming =&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm organized around interacting &amp;quot;objects&amp;quot;(usually instances of a class) rather than &amp;quot;actions&amp;quot; and data rather than logic. A basic principle of OOP is that a program consists of a list of subroutines which can perform individually. &lt;br /&gt;
&lt;br /&gt;
An object-oriented programming language provides support for the following object-oriented concepts--object, class, interface and inheritance. To illustrate this idea clearly and vividly let's review the following example-- your limbs. The &amp;quot;Limbs&amp;quot; is a class. Your body has two objects of type &amp;quot;limbs&amp;quot;, named arms and legs. Their main functions are controlled/ managed by a set of biological signals sent from central nervous system( through an interface). So the nervous system is an interface which your body uses to interact with your limbs. The &amp;quot;limbs&amp;quot; is a well architected class. The &amp;quot;legs&amp;quot; has a subclass which contains &amp;quot;left leg&amp;quot; and &amp;quot;Right leg&amp;quot;. The &amp;quot;legs&amp;quot; is being re-used to create the left leg and right leg by slightly changing the properties of it. If the &amp;quot;legs&amp;quot; owns attributes like length, color of skin etc, then the subclass, which contains &amp;quot;left leg&amp;quot; and &amp;quot;right leg&amp;quot; in this case, automatically inherit these attributes( that is called inheritance).&lt;br /&gt;
&lt;br /&gt;
We could code in object-oriented paradigm as:&lt;br /&gt;
&lt;br /&gt;
  class Limbs  &lt;br /&gt;
  #define a class of limbs&lt;br /&gt;
    def initialize(limbs,length,colorofskin)&lt;br /&gt;
    @limbs=limbs&lt;br /&gt;
    @length=length&lt;br /&gt;
    @colorofskin=colorofskin&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  limbs=Limbs.new(&amp;quot;legs&amp;quot;,&amp;quot;100cm&amp;quot;,&amp;quot;white&amp;quot;)  &lt;br /&gt;
  #create a new object in class &amp;quot;Limbs&amp;quot;&lt;br /&gt;
  class Legs&amp;lt;Limbs   &lt;br /&gt;
  #create a subclass &amp;quot;Legs&amp;quot;,which belong to class&amp;quot;Limbs&amp;quot;&lt;br /&gt;
    def initialize(legs,length,colorofskin)&lt;br /&gt;
      super(length,colorofskin)&lt;br /&gt;
      @legs=legs&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
  legs=legs.new(&amp;quot;left leg&amp;quot;) &lt;br /&gt;
  #create a new object in class of &amp;quot;Legs&amp;quot;&lt;br /&gt;
&lt;br /&gt;
== Features of Object-oriented Programming ==&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]. A programmer can simply create a new object that inherits many of its features from super-class. And also, they can overwrite existing operations or add new ones.This makes object-oriented programs easier to modify.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation].This refers to hiding the internal representation of the object from the outside view. You can hide unnecessary implementation details from the object user. One of the benefits of encapsulation is data protection.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism].This allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Consider the operator '+', for numbers it will generate the sum, but for strings it will produce a third string which concatenates the input strings.&lt;br /&gt;
&lt;br /&gt;
== Advantages of Object-oriented Programming ==&lt;br /&gt;
* Simplicity: we use software objects to simulate real world objects, so the complexity is reduced and the program structure is very clear.&lt;br /&gt;
* Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.&lt;br /&gt;
* Modifiability: programmers can easily make minor changes in the data representation or operations in an OOP. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.&lt;br /&gt;
* Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.&lt;br /&gt;
* Maintainability: objects can be maintained separately, making locating and fixing problems easier.&lt;br /&gt;
* Re-usability: objects can be reused in different programs.&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
In object-oriented world, data and operations are grouped together into modular units called objects and we combine objects into structured networks to form a program. The results are depend on arguments and objects' state at method invocation time. While in functional world, the basic elements are variables in the mathematical sense and functions in the mathematical sense. Functional programming can reduce side-effects. If there is no side-effects, it means your can apply the function at anywhere freely. No matter how you apply this function, the same input arguments produce the same results.&lt;br /&gt;
&lt;br /&gt;
According to above-mentioned information, we can perform functional programming on an object-oriented programming language because:&lt;br /&gt;
1). object can have constant state &lt;br /&gt;
2). method can depend only on its arguments and context available at method definition time&lt;br /&gt;
&lt;br /&gt;
Combining both these paradigms not only provide us a robust design structure, but also enable the programmers to develop solutions to complex problems quickly and effectively. One of the cornerstone of mixing functional and object-oriented code is treating functions as objects.It means that we can pass functions as arguments, store it and return them from other functions. This is highly useful in an user interface code where it can be used as call back functions which gets called when an event occurs(event driven programming).&lt;br /&gt;
&lt;br /&gt;
Some of the basic features of Functional Programming which can be combined with Object Oriented paradigm are:&lt;br /&gt;
&lt;br /&gt;
* Lambda Calculus&lt;br /&gt;
* Currying&lt;br /&gt;
* Powerful pattern matching&lt;br /&gt;
&lt;br /&gt;
Let us now understand how each of the above feature of Functional language fits in the Object Oriented paradigm.&lt;br /&gt;
&lt;br /&gt;
=== Lambda Calculus ===&lt;br /&gt;
Lambda calculus is the most critical basis of functional programming. A lambda expression is an anonymous expression that contain expressions and statements.Each expression stands for a function with one parameter. &lt;br /&gt;
&lt;br /&gt;
Let consider the following function:&lt;br /&gt;
&lt;br /&gt;
  def f(x)&lt;br /&gt;
  return x**2 &lt;br /&gt;
  print f(4)&lt;br /&gt;
&lt;br /&gt;
We can use a lambda calculus to compute this expression without assigning it to a variable: &lt;br /&gt;
&lt;br /&gt;
  (lambda x:x**x)(4)  &lt;br /&gt;
&lt;br /&gt;
We can see that these two code snippets have the same results. It is more concise and flexible to define with lambda.&lt;br /&gt;
The above is a pure functional approach. In order to make code more state-less and concise, lambdas can be embedded inside the object-oriented language. The below code in Python demonstrates the use of lambda in a closure:&lt;br /&gt;
&lt;br /&gt;
  def fun(x):&lt;br /&gt;
    return x%3==0&lt;br /&gt;
    str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
    filter(fun,str)&lt;br /&gt;
&lt;br /&gt;
The above code works to find numbers which are divisible by 3.&lt;br /&gt;
We can simplify the code by the use of lambda as following:&lt;br /&gt;
&lt;br /&gt;
  str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
  print filter(lambda x: x%3==0, str)&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
In the above information we have learned much about lambda calculus, which take care of one argument, now let me introduce you another concept called currying functions which takes in multiple arguments and returns a chain of functions with lesser number of arguments. It can be interpreted as the technique to decompose a function that takes n parameters into n functions and each of the n functions takes one parameter. &lt;br /&gt;
&lt;br /&gt;
Currying is really an interesting concept. Let's take a sample code in JavaScript to understand it: &lt;br /&gt;
&lt;br /&gt;
  //This is a function for calculating x+y. The difference between this function and general is that this is a currying function.&lt;br /&gt;
  function add(x, y)&lt;br /&gt;
  {&lt;br /&gt;
  if(x!=null &amp;amp;&amp;amp; y!=null) return x + y;&lt;br /&gt;
  else if(x!=null &amp;amp;&amp;amp; y==null) return function(y)&lt;br /&gt;
   { &lt;br /&gt;
     return x + y;  //return a closure with parameter y for subsequent calculations&lt;br /&gt;
    }&lt;br /&gt;
  else if(x==null &amp;amp;&amp;amp; y!=null) return function(x)&lt;br /&gt;
   {&lt;br /&gt;
     return x + y;  //return a closure with parameter x for subsequent calculations&lt;br /&gt;
    }&lt;br /&gt;
   }&lt;br /&gt;
  var a = add(3, 4);  //compute the value of (3+4) and return the value of 7&lt;br /&gt;
  var b = add(2);  //add(2) is equal to a function of (2+y)&lt;br /&gt;
  var c = b(10);  //pass 10 to y, and return the value of (2+10) which is 12&lt;br /&gt;
&lt;br /&gt;
In the above sample, b=add(2) gives us a currying function of add(), which is function of y when x=2.&lt;br /&gt;
&lt;br /&gt;
More interestingly, we can define a currying form of arbitrary functions.&lt;br /&gt;
  function Foo(x, y, z, w)&lt;br /&gt;
  {&lt;br /&gt;
   var args = arguments;&lt;br /&gt;
   if(Foo.length &amp;lt; args.length)&lt;br /&gt;
     return function()&lt;br /&gt;
    {&lt;br /&gt;
      return args.callee.apply(Array.apply([], args).concat(Array.apply([], arguments)));&lt;br /&gt;
    }&lt;br /&gt;
   else&lt;br /&gt;
     return x + y – z * w;&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
What is pattern matching? I think all of you do know what it is, you just don't know you know it. The semantics are equally straightforward.Firstly, we evaluate the value expression, then we walk down the clauses. For each one, we see if the pattern matches the value. If so, we execute the body and end. Simply put, pattern matching is a technique to search string for the occurrence of any patterns or regularity. &lt;br /&gt;
&lt;br /&gt;
Pattern matching allows you to do different calculations according to different identifier values. It looks the same with nests of &amp;quot;if...else&amp;quot; statements, as well as &amp;quot;switch&amp;quot; statements in C++ and C#. But here it is much stronger and more flexible. &lt;br /&gt;
&lt;br /&gt;
You may find that there are two main types of usage of pattern matching:&lt;br /&gt;
* To search and find a particular value.&lt;br /&gt;
* To find a particular value and replace it with selected text. &lt;br /&gt;
&lt;br /&gt;
For example, the following code snippets writes a message if a string contains the text Perl or Python:&lt;br /&gt;
&lt;br /&gt;
  if line =~ /Perl|Python/&lt;br /&gt;
  puts &amp;quot;Scripting language mentioned:#{line}&amp;quot;  &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Next, let us consider the following sample in which a part of a string matched by a regular expression can be replaced with different text using one of Ruby’s substitution methods:&lt;br /&gt;
&lt;br /&gt;
  line.sub(/Perl/, 'Ruby') # replace first 'Perl' with 'Ruby'&lt;br /&gt;
  line.gsub(/Python/, 'Ruby') # replace every 'Python' with 'Ruby'&lt;br /&gt;
&lt;br /&gt;
Advantages of Pattern Matching:&lt;br /&gt;
* It allows concise, readable deconstruction of complex data structures.&lt;br /&gt;
* It gives a possible separation of data structure and respective functionality.&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
A number of programming languages support mixing of both functional and object-oriented code. Three of these (Scala, Ruby, and Conjure), are described in more detail below.&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky. It supports mixing functional and object-oriented code.&lt;br /&gt;
&lt;br /&gt;
==== Mixing Functional and Object-Oriented Code in Scala ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object-oriented and functional programming. How can this happen? The functional world advocates immutability, but the object-oriented world focuses on the state and how to change it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . A rough translation into Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as:&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks much simpler and less verbose. Even though the above example shows an immutable collection, scala also provides mutable collections and object types in the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So it's the best of both worlds. Another part of the functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
==== Implicits in Scala ====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. Since you are splitting open the class and adding/overriding methods (in)|(to) the class, this feature is often called [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching]. Because other libraries may depend on some methods which you changed, often this leads to unexpected behavior at runtime. However, Scala provides yet another feature called [http://en.wikipedia.org/wiki/Implicit_function implicits] which helps you do this better.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Ruby is another language that, like Scala, supports mixing functional and object-oriented code. It is a dynamically typed Object-Oriented Language which supports multiple programming paradigms, including functional, object-oriented, imperative and reflective. In Ruby, everything is an object, every bit of information and code can have its own properties and actions. However, Ruby’s blocks can be functional. A Ruby programmer can attach a closure to any method, which generates a functional block inside an object oriented code. A closure is a piece of code that can access the lexical environment of its definition [http://www.ruby-lang.org/en/ 11].&lt;br /&gt;
&lt;br /&gt;
==== Ruby Mixing Example ====&lt;br /&gt;
&lt;br /&gt;
Consider the following code snippet in Ruby which uses Object Oriented concepts like Classes and functional programming concepts like lambda.&lt;br /&gt;
&lt;br /&gt;
 class Multiply&lt;br /&gt;
   def initialize(n)&lt;br /&gt;
     @block = lambda {|a| n * a}&lt;br /&gt;
   end&lt;br /&gt;
   def mul(a)&lt;br /&gt;
     @block.call a&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 twoMultiplier = Multiply.new 2                     &lt;br /&gt;
 puts twoMultiplier.mul(6)&lt;br /&gt;
&lt;br /&gt;
Here,'''''@block''''' is a closure. When we call the class ''Multiply'' using '''''twoAdder = Multiply.new 2''''' ,the ''initialize'' method is called by passing the parameter 2. Here n=2 binds itself to the block. So @block will be 2*a, that is,the closure remembers the parameter with which the initialize method was called even after the initialize method exits.  &lt;br /&gt;
&lt;br /&gt;
This value is used when the block is called in the add method.  &lt;br /&gt;
Thus,'''''twoMultiplier.mul(6)''''' will return 2*6 = 12&lt;br /&gt;
&lt;br /&gt;
==== Functional Style Coding in Ruby Blocks ====&lt;br /&gt;
&lt;br /&gt;
Blocks are basically nameless functions which can be passed to a function and then that function can invoke the passed in nameless function. This is a common style called [http://en.wikipedia.org/wiki/Higher-order_function higher order functions] among languages that handle functions as first class objects. Basically blocks can be designed for loop abstraction and lets the user to design their own way of iterating the values, thereby hiding the implementation details. &lt;br /&gt;
For example, if we want to iterate backwards from the end to the beginning without revealing its internal implementations, we could implement the loop logic inside the block and pass it to a method or function.&lt;br /&gt;
&lt;br /&gt;
Here is a [http://www.ruby-lang.org/en/ Ruby] implementation of block:&lt;br /&gt;
 &lt;br /&gt;
 def printlist(array,&amp;amp;reverse)&lt;br /&gt;
    array.each do |element|&lt;br /&gt;
       puts &amp;quot;array element: #{element}&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
    reverse.call(array)   /* Here it prints the reverse implementation of list*/&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
 printlist([1,2,3,4,5,6]) { |array| &lt;br /&gt;
   array.reverse.each do |element| &lt;br /&gt;
     puts &amp;quot;array element: #{element}&amp;quot; &lt;br /&gt;
   end &lt;br /&gt;
 }&lt;br /&gt;
The statements between { } is a block and it gets called by &amp;lt;code&amp;gt;reverse.call(array)&amp;lt;/code&amp;gt;within the printlist method.&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 31]] is also a functional programming language, and it is a dialect of Lisp. It is not a pure functional language. Instead, it is a dynamically typed language. Just like Java it runs on JVM platform, but its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
(functions arguments...)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The function and its arguments are enclosed in paranthesis. It has features like immutable data structures, high-order functions, recursion, and easy and fast java interoperability. &lt;br /&gt;
&lt;br /&gt;
In Clojure's model, value calculation is purely functional. Values never change. New values are functions of old. But, logical identity is well supported via atomic references to values. The value of a reference (state of an identity) is always observable without coordination and freely shareable between threads.&lt;br /&gt;
When programs are constructed this way, functional value calculation is independent of identity-value association. This makes clojure easier to understand and test.&lt;br /&gt;
&lt;br /&gt;
====Example Using Functional Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
Consider the following functional programming example in Clojure-&lt;br /&gt;
 (defn make-adder [x]&lt;br /&gt;
   (let [y x]&lt;br /&gt;
     (fn [z] (+ y z))))&lt;br /&gt;
 (def add2 (make-adder 2))&lt;br /&gt;
 (add2 4)&lt;br /&gt;
&lt;br /&gt;
Here,'''''defn make-adder [x]''''' defines a function called ''make-adder''.'''''let [y x]''''' gives a local name y for the value x. Since the scope of any local names is lexical, a function created in the scope of local names will close over their values.'''''fn [z] (+ y z)''''' does the addition of y and z.&lt;br /&gt;
''&lt;br /&gt;
'''def add2 (make-adder 2)''''' calls the function ''make-adder'' passing the parameter 2 and calls this as ''add2''.Now, ''add2'' has computed 2+z. When '''''add2 4''''' is called it computes 2+4=6&lt;br /&gt;
&lt;br /&gt;
====Example Using Object-Oriented Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
The following program implements Run-Time Polymorphism which is an object-oriented programming concept.&lt;br /&gt;
 (defmulti encounter (fn [x y] [(:Species x) (:Species y)]))&lt;br /&gt;
 (defmethod encounter [:Bunny :Lion] [b l] :run-away)&lt;br /&gt;
 (defmethod encounter [:Lion :Bunny] [l b] :eat)&lt;br /&gt;
 (defmethod encounter [:Lion :Lion] [l1 l2] :fight)&lt;br /&gt;
 (defmethod encounter [:Bunny :Bunny] [b1 b2] :mate)&lt;br /&gt;
 (def b1 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def b2 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def l1 {:Species :Lion :other :stuff})&lt;br /&gt;
 (def l2 {:Species :Lion :other :stuff})&lt;br /&gt;
 &lt;br /&gt;
 (encounter b1 l1)&lt;br /&gt;
 -&amp;gt; :run-away&lt;br /&gt;
 (encounter l1 l2)&lt;br /&gt;
 -&amp;gt; :fight&lt;br /&gt;
&lt;br /&gt;
Here,'''''defmulti''''' is used to define multiple methods which have the same method name '''''encounter'''''.Depending on the parameters passed to the encounter method, one of the four methods is called.&lt;br /&gt;
'''''def''''' defines each of the different species.&lt;br /&gt;
When, '''''(encounter b1 l1)''''' is called, the first ''encounter'' method is called with the parameters ''Bunny'' and ''Lion''. As a result, ''run-away'' is printed.&lt;br /&gt;
&lt;br /&gt;
=== Summary of Languages Supporting Mixing ===&lt;br /&gt;
&lt;br /&gt;
Each of the languages contains both functional and object-oriented features. The following table shows how each of the languages have both functional and object-oriented characterics. Not all characteristics of the languages are listed, but enough to demonstrate that the languages each have different ways of mixing object-oriented and functional techniques.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  &lt;br /&gt;
!  Functional Characteristics&lt;br /&gt;
!  Object-Oriented Characteristics&lt;br /&gt;
|-&lt;br /&gt;
! Scala&lt;br /&gt;
| Immutable objects, the ability to pass functions as parameters, implicits, closures.&lt;br /&gt;
| Every value is a object, mutable objects.&lt;br /&gt;
|-&lt;br /&gt;
! Ruby&lt;br /&gt;
| Functional programming used in blocks.&lt;br /&gt;
| Everything is an object.&lt;br /&gt;
|-&lt;br /&gt;
! Clojure&lt;br /&gt;
| Immutable data structures, high-order functions, recursion.&lt;br /&gt;
| Objects, runtime polymorphism, [http://en.wikipedia.org/wiki/Multiple_dispatch multimethods.]&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
In summary, functional and object-oriented programming can be successfully mixed in programs. Many functional techniques are useful in object-oriented programs. Languages such as Scala, Ruby, and Clojure effectively support mixing these two paradigms, allowing programmers to create cleaner, less buggy object-oriented code.&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Functional_programming Wikipedia - Functional Programming]&lt;br /&gt;
#[http://www.cs.cornell.edu/riccardo/prog-smlnj/notes-011001.pdf Notes on programming Standard ML of New Jersey]&lt;br /&gt;
#[http://users.dickinson.edu/~braught/courses/cs132f01/classes/code/Factorial.src.html Introduction to Computing - Dickinson College]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Object-oriented_programming Wikipedia - Object Oriented Programming]&lt;br /&gt;
#[http://searchsoa.techtarget.com/sDefinition/0,,sid26_gci212681,00.html  More on Object Oriented Programming]&lt;br /&gt;
#[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas Understanding Ruby Blocks, Procs and Lambdas - Robert Sosinski]&lt;br /&gt;
#[http://www.codingday.com/power-of-functional-programming-its-features-and-its-future/ Power of Functional Programming, its Features and its Future]&lt;br /&gt;
#[http://skillsmatter.com/podcast/open-source-dot-net/mike-wagg-mark-needham-functional-and-oo-approaches-to-c-sharp-programming Mixing Functional and Object Oriented Approaches to Programming in C#]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigm]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Recursion Recursion]&lt;br /&gt;
#[http://www.scala-lang.org/ Scala]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Scala_%28programming_language%29 Scala Wikipedia]&lt;br /&gt;
#[http://clojure.org/ Clojure]&lt;br /&gt;
#[http://www.ruby-lang.org/en/ Ruby]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Standard_ML Standard ML]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Haskell_%28programming_language%29 Haskell]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/ML_%28programming_language%29 ML Family]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/C%2B%2B C++ Programming Language]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Visual_Basic_.NET Visual Basic .Net]&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;br /&gt;
#O'Reilly (2009), &amp;quot;Programming Scala&amp;quot;, ''O'Reilly Media Inc.''.&lt;br /&gt;
#Dave Thomas, Chad Fowler, Andy Hunt (2006) ''Programming Ruby'', The Pragmatic Bookshelf.&lt;br /&gt;
#[http://lamp.epfl.ch/~phaller/doc/haller10-Translucent_functions.pdf Philipp Halle, Lightweight language support for type-based, concurrent event processing, Lausanne, Switzerland, April 2010.]&lt;br /&gt;
#[http://biblion.epfl.ch/EPFL/theses/2007/3899/EPFL_TH3899.pdf Burak Emir, Object-Oriented Pattern Matching, EPFL, October 2007].&lt;br /&gt;
#[http://math.hws.edu/eck/cs124/downloads/OOP2_from_Univ_KwaZulu-Natal.pdf, Object-Oriented Programming,February 2007].&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63497</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63497"/>
		<updated>2012-09-11T02:21:22Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Functional Programming */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and mandates that data is [http://en.wikipedia.org/wiki/Immutable immutable]. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
== Example Contrasting Imperitive and Functional Styles ==&lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily. &lt;br /&gt;
&lt;br /&gt;
== Advantages of Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-oriented Programming =&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm organized around interacting &amp;quot;objects&amp;quot;(usually instances of a class) rather than &amp;quot;actions&amp;quot; and data rather than logic. A basic principle of OOP is that a program consists of a list of subroutines which can perform individually. &lt;br /&gt;
&lt;br /&gt;
An object-oriented programming language provides support for the following object-oriented concepts--object, class, interface and inheritance. To illustrate this idea clearly and vividly let's review the following example-- your limbs. The &amp;quot;Limbs&amp;quot; is a class. Your body has two objects of type &amp;quot;limbs&amp;quot;, named arms and legs. Their main functions are controlled/ managed by a set of biological signals sent from central nervous system( through an interface). So the nervous system is an interface which your body uses to interact with your limbs. The &amp;quot;limbs&amp;quot; is a well architected class. The &amp;quot;legs&amp;quot; has a subclass which contains &amp;quot;left leg&amp;quot; and &amp;quot;Right leg&amp;quot;. The &amp;quot;legs&amp;quot; is being re-used to create the left leg and right leg by slightly changing the properties of it. If the &amp;quot;legs&amp;quot; owns attributes like length, color of skin etc, then the subclass, which contains &amp;quot;left leg&amp;quot; and &amp;quot;right leg&amp;quot; in this case, automatically inherit these attributes( that is called inheritance).&lt;br /&gt;
&lt;br /&gt;
We could code in object-oriented paradigm as:&lt;br /&gt;
&lt;br /&gt;
  class Limbs  /*define a class of limbs*/&lt;br /&gt;
    def initialize(limbs,length,colorofskin)&lt;br /&gt;
    @limbs=limbs&lt;br /&gt;
    @length=length&lt;br /&gt;
    @colorofskin=colorofskin&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  limbs=Limbs.new(&amp;quot;legs&amp;quot;,&amp;quot;100cm&amp;quot;,&amp;quot;white&amp;quot;)  /*create a new object in class &amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
  class Legs&amp;lt;Limbs   /*create a subclass &amp;quot;Legs&amp;quot;,which belong to class&amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
    def initialize(legs,length,colorofskin)&lt;br /&gt;
      super(length,colorofskin)&lt;br /&gt;
      @legs=legs&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
  legs=legs.new(&amp;quot;left leg&amp;quot;) /*create a new object in class of &amp;quot;Legs&amp;quot;*/&lt;br /&gt;
&lt;br /&gt;
== Features of Object-oriented Programming ==&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]. A programmer can simply create a new object that inherits many of its features from super-class. And also, they can overwrite existing operations or add new ones.This makes object-oriented programs easier to modify.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation].This refers to hiding the internal representation of the object from the outside view. You can hide unnecessary implementation details from the object user. One of the benefits of encapsulation is data protection.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism].This allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Consider the operator '+', for numbers it will generate the sum, but for strings it will produce a third string which concatenates the input strings.&lt;br /&gt;
&lt;br /&gt;
== Advantages of Object-oriented Programming ==&lt;br /&gt;
* Simplicity: we use software objects to simulate real world objects, so the complexity is reduced and the program structure is very clear.&lt;br /&gt;
* Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.&lt;br /&gt;
* Modifiability: programmers can easily make minor changes in the data representation or operations in an OOP. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.&lt;br /&gt;
* Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.&lt;br /&gt;
* Maintainability: objects can be maintained separately, making locating and fixing problems easier.&lt;br /&gt;
* Re-usability: objects can be reused in different programs.&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
In object-oriented world, data and operations are grouped together into modular units called objects and we combine objects into structured networks to form a program. The results are depend on arguments and objects' state at method invocation time. While in functional world, the basic elements are variables in the mathematical sense and functions in the mathematical sense. Functional programming can reduce side-effects. If there is no side-effects, it means your can apply the function at anywhere freely. No matter how you apply this function, the same input arguments produce the same results.&lt;br /&gt;
&lt;br /&gt;
According to above-mentioned information, we can perform functional programming on an object-oriented programming language because:&lt;br /&gt;
1). object can have constant state &lt;br /&gt;
2). method can depend only on its arguments and context available at method definition time&lt;br /&gt;
&lt;br /&gt;
Combining both these paradigms not only provide us a robust design structure, but also enable the programmers to develop solutions to complex problems quickly and effectively. One of the cornerstone of mixing functional and object-oriented code is treating functions as objects.It means that we can pass functions as arguments, store it and return them from other functions. This is highly useful in an user interface code where it can be used as call back functions which gets called when an event occurs(event driven programming).&lt;br /&gt;
&lt;br /&gt;
Some of the basic features of Functional Programming which can be combined with Object Oriented paradigm are:&lt;br /&gt;
&lt;br /&gt;
* Lambda Calculus&lt;br /&gt;
* Currying&lt;br /&gt;
* Powerful pattern matching&lt;br /&gt;
&lt;br /&gt;
Let us now understand how each of the above feature of Functional language fits in the Object Oriented paradigm.&lt;br /&gt;
&lt;br /&gt;
=== Lambda Calculus ===&lt;br /&gt;
Lambda calculus is the most critical basis of functional programming. A lambda expression is an anonymous expression that contain expressions and statements.Each expression stands for a function with one parameter. &lt;br /&gt;
&lt;br /&gt;
Let consider the following function:&lt;br /&gt;
&lt;br /&gt;
  def f(x)&lt;br /&gt;
  return x**2 &lt;br /&gt;
  print f(4)&lt;br /&gt;
&lt;br /&gt;
We can use a lambda calculus to compute this expression without assigning it to a variable: &lt;br /&gt;
&lt;br /&gt;
  (lambda x:x**x)(4)  &lt;br /&gt;
&lt;br /&gt;
We can see that these two code snippets have the same results. It is more concise and flexible to define with lambda.&lt;br /&gt;
The above is a pure functional approach. In order to make code more state-less and concise, lambdas can be embedded inside the object-oriented language. The below code in Python demonstrates the use of lambda in a closure:&lt;br /&gt;
&lt;br /&gt;
  def fun(x):&lt;br /&gt;
    return x%3==0&lt;br /&gt;
    str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
    filter(fun,str)&lt;br /&gt;
&lt;br /&gt;
The above code works to find numbers which are divisible by 3.&lt;br /&gt;
We can simplify the code by the use of lambda as following:&lt;br /&gt;
&lt;br /&gt;
  str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
  print filter(lambda x: x%3==0, str)&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
A number of programming languages support mixing of both functional and object-oriented code. Three of these (Scala, Ruby, and Conjure), are described in more detail below.&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky. It supports mixing functional and object-oriented code.&lt;br /&gt;
&lt;br /&gt;
==== Mixing Functional and Object-Oriented Code in Scala ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object-oriented and functional programming. How can this happen? The functional world advocates immutability, but the object-oriented world focuses on the state and how to change it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . A rough translation into Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as:&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks much simpler and less verbose. Even though the above example shows an immutable collection, scala also provides mutable collections and object types in the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So it's the best of both worlds. Another part of the functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
==== Implicits in Scala ====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. Since you are splitting open the class and adding/overriding methods (in)|(to) the class, this feature is often called [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching]. Because other libraries may depend on some methods which you changed, often this leads to unexpected behavior at runtime. However, Scala provides yet another feature called [http://en.wikipedia.org/wiki/Implicit_function implicits] which helps you do this better.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Ruby is another language that, like Scala, supports mixing functional and object-oriented code. It is a dynamically typed Object-Oriented Language which supports multiple programming paradigms, including functional, object-oriented, imperative and reflective. In Ruby, everything is an object, every bit of information and code can have its own properties and actions. However, Ruby’s blocks can be functional. A Ruby programmer can attach a closure to any method, which generates a functional block inside an object oriented code. A closure is a piece of code that can access the lexical environment of its definition [http://www.ruby-lang.org/en/ 11].&lt;br /&gt;
&lt;br /&gt;
==== Ruby Mixing Example ====&lt;br /&gt;
&lt;br /&gt;
Consider the following code snippet in Ruby which uses Object Oriented concepts like Classes and functional programming concepts like lambda.&lt;br /&gt;
&lt;br /&gt;
 class Multiply&lt;br /&gt;
   def initialize(n)&lt;br /&gt;
     @block = lambda {|a| n * a}&lt;br /&gt;
   end&lt;br /&gt;
   def mul(a)&lt;br /&gt;
     @block.call a&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 twoMultiplier = Multiply.new 2                     &lt;br /&gt;
 puts twoMultiplier.mul(6)&lt;br /&gt;
&lt;br /&gt;
Here,'''''@block''''' is a closure. When we call the class ''Multiply'' using '''''twoAdder = Multiply.new 2''''' ,the ''initialize'' method is called by passing the parameter 2. Here n=2 binds itself to the block. So @block will be 2*a, that is,the closure remembers the parameter with which the initialize method was called even after the initialize method exits.  &lt;br /&gt;
&lt;br /&gt;
This value is used when the block is called in the add method.  &lt;br /&gt;
Thus,'''''twoMultiplier.mul(6)''''' will return 2*6 = 12&lt;br /&gt;
&lt;br /&gt;
==== Functional Style Coding in Ruby Blocks ====&lt;br /&gt;
&lt;br /&gt;
Blocks are basically nameless functions which can be passed to a function and then that function can invoke the passed in nameless function. This is a common style called [http://en.wikipedia.org/wiki/Higher-order_function higher order functions] among languages that handle functions as first class objects. Basically blocks can be designed for loop abstraction and lets the user to design their own way of iterating the values, thereby hiding the implementation details. &lt;br /&gt;
For example, if we want to iterate backwards from the end to the beginning without revealing its internal implementations, we could implement the loop logic inside the block and pass it to a method or function.&lt;br /&gt;
&lt;br /&gt;
Here is a [http://www.ruby-lang.org/en/ Ruby] implementation of block:&lt;br /&gt;
 &lt;br /&gt;
 def printlist(array,&amp;amp;reverse)&lt;br /&gt;
    array.each do |element|&lt;br /&gt;
       puts &amp;quot;array element: #{element}&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
    reverse.call(array)   /* Here it prints the reverse implementation of list*/&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
 printlist([1,2,3,4,5,6]) { |array| &lt;br /&gt;
   array.reverse.each do |element| &lt;br /&gt;
     puts &amp;quot;array element: #{element}&amp;quot; &lt;br /&gt;
   end &lt;br /&gt;
 }&lt;br /&gt;
The statements between { } is a block and it gets called by &amp;lt;code&amp;gt;reverse.call(array)&amp;lt;/code&amp;gt;within the printlist method.&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 31]] is also a functional programming language, and it is a dialect of Lisp. It is not a pure functional language. Instead, it is a dynamically typed language. Just like Java it runs on JVM platform, but its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
(functions arguments...)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The function and its arguments are enclosed in paranthesis. It has features like immutable data structures, high-order functions, recursion, and easy and fast java interoperability. &lt;br /&gt;
&lt;br /&gt;
In Clojure's model, value calculation is purely functional. Values never change. New values are functions of old. But, logical identity is well supported via atomic references to values. The value of a reference (state of an identity) is always observable without coordination and freely shareable between threads.&lt;br /&gt;
When programs are constructed this way, functional value calculation is independent of identity-value association. This makes clojure easier to understand and test.&lt;br /&gt;
&lt;br /&gt;
====Example Using Functional Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
Consider the following functional programming example in Clojure-&lt;br /&gt;
 (defn make-adder [x]&lt;br /&gt;
   (let [y x]&lt;br /&gt;
     (fn [z] (+ y z))))&lt;br /&gt;
 (def add2 (make-adder 2))&lt;br /&gt;
 (add2 4)&lt;br /&gt;
&lt;br /&gt;
Here,'''''defn make-adder [x]''''' defines a function called ''make-adder''.'''''let [y x]''''' gives a local name y for the value x. Since the scope of any local names is lexical, a function created in the scope of local names will close over their values.'''''fn [z] (+ y z)''''' does the addition of y and z.&lt;br /&gt;
''&lt;br /&gt;
'''def add2 (make-adder 2)''''' calls the function ''make-adder'' passing the parameter 2 and calls this as ''add2''.Now, ''add2'' has computed 2+z. When '''''add2 4''''' is called it computes 2+4=6&lt;br /&gt;
&lt;br /&gt;
====Example Using Object-Oriented Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
The following program implements Run-Time Polymorphism which is an object-oriented programming concept.&lt;br /&gt;
 (defmulti encounter (fn [x y] [(:Species x) (:Species y)]))&lt;br /&gt;
 (defmethod encounter [:Bunny :Lion] [b l] :run-away)&lt;br /&gt;
 (defmethod encounter [:Lion :Bunny] [l b] :eat)&lt;br /&gt;
 (defmethod encounter [:Lion :Lion] [l1 l2] :fight)&lt;br /&gt;
 (defmethod encounter [:Bunny :Bunny] [b1 b2] :mate)&lt;br /&gt;
 (def b1 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def b2 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def l1 {:Species :Lion :other :stuff})&lt;br /&gt;
 (def l2 {:Species :Lion :other :stuff})&lt;br /&gt;
 &lt;br /&gt;
 (encounter b1 l1)&lt;br /&gt;
 -&amp;gt; :run-away&lt;br /&gt;
 (encounter l1 l2)&lt;br /&gt;
 -&amp;gt; :fight&lt;br /&gt;
&lt;br /&gt;
Here,'''''defmulti''''' is used to define multiple methods which have the same method name '''''encounter'''''.Depending on the parameters passed to the encounter method, one of the four methods is called.&lt;br /&gt;
'''''def''''' defines each of the different species.&lt;br /&gt;
When, '''''(encounter b1 l1)''''' is called, the first ''encounter'' method is called with the parameters ''Bunny'' and ''Lion''. As a result, ''run-away'' is printed.&lt;br /&gt;
&lt;br /&gt;
=== Summary of Languages Supporting Mixing ===&lt;br /&gt;
&lt;br /&gt;
Each of the languages contains both functional and object-oriented features. The following table shows how each of the languages have both functional and object-oriented characterics. Not all characteristics of the languages are listed, but enough to demonstrate that the languages each have different ways of mixing object-oriented and functional techniques.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  &lt;br /&gt;
!  Functional Characteristics&lt;br /&gt;
!  Object-Oriented Characteristics&lt;br /&gt;
|-&lt;br /&gt;
! Scala&lt;br /&gt;
| Immutable objects, the ability to pass functions as parameters, implicits, closures.&lt;br /&gt;
| Every value is a object, mutable objects.&lt;br /&gt;
|-&lt;br /&gt;
! Ruby&lt;br /&gt;
| Functional programming used in blocks.&lt;br /&gt;
| Everything is an object.&lt;br /&gt;
|-&lt;br /&gt;
! Clojure&lt;br /&gt;
| Immutable data structures, high-order functions, recursion.&lt;br /&gt;
| Objects, runtime polymorphism, [http://en.wikipedia.org/wiki/Multiple_dispatch multimethods.]&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Functional_programming Wikipedia - Functional Programming]&lt;br /&gt;
#[http://www.cs.cornell.edu/riccardo/prog-smlnj/notes-011001.pdf Notes on programming Standard ML of New Jersey]&lt;br /&gt;
#[http://users.dickinson.edu/~braught/courses/cs132f01/classes/code/Factorial.src.html Introduction to Computing - Dickinson College]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Object-oriented_programming Wikipedia - Object Oriented Programming]&lt;br /&gt;
#[http://searchsoa.techtarget.com/sDefinition/0,,sid26_gci212681,00.html  More on Object Oriented Programming]&lt;br /&gt;
#[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas Understanding Ruby Blocks, Procs and Lambdas - Robert Sosinski]&lt;br /&gt;
#[http://www.codingday.com/power-of-functional-programming-its-features-and-its-future/ Power of Functional Programming, its Features and its Future]&lt;br /&gt;
#[http://skillsmatter.com/podcast/open-source-dot-net/mike-wagg-mark-needham-functional-and-oo-approaches-to-c-sharp-programming Mixing Functional and Object Oriented Approaches to Programming in C#]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigm]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Recursion Recursion]&lt;br /&gt;
#[http://www.scala-lang.org/ Scala]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Scala_%28programming_language%29 Scala Wikipedia]&lt;br /&gt;
#[http://clojure.org/ Clojure]&lt;br /&gt;
#[http://www.ruby-lang.org/en/ Ruby]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Standard_ML Standard ML]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Haskell_%28programming_language%29 Haskell]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/ML_%28programming_language%29 ML Family]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/C%2B%2B C++ Programming Language]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Visual_Basic_.NET Visual Basic .Net]&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;br /&gt;
#O'Reilly (2009), &amp;quot;Programming Scala&amp;quot;, ''O'Reilly Media Inc.''.&lt;br /&gt;
#Dave Thomas, Chad Fowler, Andy Hunt (2006) ''Programming Ruby'', The Pragmatic Bookshelf.&lt;br /&gt;
#[http://lamp.epfl.ch/~phaller/doc/haller10-Translucent_functions.pdf Philipp Halle, Lightweight language support for type-based, concurrent event processing, Lausanne, Switzerland, April 2010.]&lt;br /&gt;
#[http://biblion.epfl.ch/EPFL/theses/2007/3899/EPFL_TH3899.pdf Burak Emir, Object-Oriented Pattern Matching, EPFL, October 2007].&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63492</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63492"/>
		<updated>2012-09-11T02:14:11Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Examples of Mixing */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and data is immutable****. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily. &lt;br /&gt;
&lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-oriented Programming =&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm organized around interacting &amp;quot;objects&amp;quot;(usually instances of a class) rather than &amp;quot;actions&amp;quot; and data rather than logic. A basic principle of OOP is that a program consists of a list of subroutines which can perform individually. &lt;br /&gt;
&lt;br /&gt;
An object-oriented programming language provides support for the following object-oriented concepts--object, class, interface and inheritance. To illustrate this idea clearly and vividly let's review the following example-- your limbs. The &amp;quot;Limbs&amp;quot; is a class. Your body has two objects of type &amp;quot;limbs&amp;quot;, named arms and legs. Their main functions are controlled/ managed by a set of biological signals sent from central nervous system( through an interface). So the nervous system is an interface which your body uses to interact with your limbs. The &amp;quot;limbs&amp;quot; is a well architected class. The &amp;quot;legs&amp;quot; has a subclass which contains &amp;quot;left leg&amp;quot; and &amp;quot;Right leg&amp;quot;. The &amp;quot;legs&amp;quot; is being re-used to create the left leg and right leg by slightly changing the properties of it. If the &amp;quot;legs&amp;quot; owns attributes like length, color of skin etc, then the subclass, which contains &amp;quot;left leg&amp;quot; and &amp;quot;right leg&amp;quot; in this case, automatically inherit these attributes( that is called inheritance).&lt;br /&gt;
&lt;br /&gt;
We could code in object-oriented paradigm as:&lt;br /&gt;
&lt;br /&gt;
  class Limbs  /*define a class of limbs*/&lt;br /&gt;
    def initialize(limbs,length,colorofskin)&lt;br /&gt;
    @limbs=limbs&lt;br /&gt;
    @length=length&lt;br /&gt;
    @colorofskin=colorofskin&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  limbs=Limbs.new(&amp;quot;legs&amp;quot;,&amp;quot;100cm&amp;quot;,&amp;quot;white&amp;quot;)  /*create a new object in class &amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
  class Legs&amp;lt;Limbs   /*create a subclass &amp;quot;Legs&amp;quot;,which belong to class&amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
    def initialize(legs,length,colorofskin)&lt;br /&gt;
      super(length,colorofskin)&lt;br /&gt;
      @legs=legs&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
  legs=legs.new(&amp;quot;left leg&amp;quot;) /*create a new object in class of &amp;quot;Legs&amp;quot;*/&lt;br /&gt;
&lt;br /&gt;
== Features of Object-oriented Programming ==&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]. A programmer can simply create a new object that inherits many of its features from super-class. And also, they can overwrite existing operations or add new ones.This makes object-oriented programs easier to modify.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation].This refers to hiding the internal representation of the object from the outside view. You can hide unnecessary implementation details from the object user. One of the benefits of encapsulation is data protection.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism].This allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Consider the operator '+', for numbers it will generate the sum, but for strings it will produce a third string which concatenates the input strings.&lt;br /&gt;
&lt;br /&gt;
== Advantages of Object-oriented Programming ==&lt;br /&gt;
* Simplicity: we use software objects to simulate real world objects, so the complexity is reduced and the program structure is very clear.&lt;br /&gt;
* Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.&lt;br /&gt;
* Modifiability: programmers can easily make minor changes in the data representation or operations in an OOP. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.&lt;br /&gt;
* Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.&lt;br /&gt;
* Maintainability: objects can be maintained separately, making locating and fixing problems easier.&lt;br /&gt;
* Re-usability: objects can be reused in different programs.&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
In object-oriented world, data and operations are grouped together into modular units called objects and we combine objects into structured networks to form a program. The results are depend on arguments and objects' state at method invocation time. While in functional world, the basic elements are variables in the mathematical sense and functions in the mathematical sense. Functional programming can reduce side-effects. If there is no side-effects, it means your can apply the function at anywhere freely. No matter how you apply this function, the same input arguments produce the same results.&lt;br /&gt;
&lt;br /&gt;
According to above-mentioned information, we can perform functional programming on an object-oriented programming language because:&lt;br /&gt;
1). object can have constant state &lt;br /&gt;
2). method can depend only on its arguments and context available at method definition time&lt;br /&gt;
&lt;br /&gt;
Combining both these paradigms not only provide us a robust design structure, but also enable the programmers to develop solutions to complex problems quickly and effectively. One of the cornerstone of mixing functional and object-oriented code is treating functions as objects.It means that we can pass functions as arguments, store it and return them from other functions. This is highly useful in an user interface code where it can be used as call back functions which gets called when an event occurs(event driven programming).&lt;br /&gt;
&lt;br /&gt;
Some of the basic features of Functional Programming which can be combined with Object Oriented paradigm are:&lt;br /&gt;
&lt;br /&gt;
* Lambda Calculus&lt;br /&gt;
* Currying&lt;br /&gt;
* Powerful pattern matching&lt;br /&gt;
&lt;br /&gt;
Let us now understand how each of the above feature of Functional language fits in the Object Oriented paradigm.&lt;br /&gt;
&lt;br /&gt;
=== Lambda Calculus ===&lt;br /&gt;
Lambda calculus is the most critical basis of functional programming. A lambda expression is an anonymous expression that contain expressions and statements.Each expression stands for a function with one parameter. &lt;br /&gt;
&lt;br /&gt;
Let consider the following function:&lt;br /&gt;
&lt;br /&gt;
  def f(x)&lt;br /&gt;
  return x**2 &lt;br /&gt;
  print f(4)&lt;br /&gt;
&lt;br /&gt;
We can use a lambda calculus to compute this expression without assigning it to a variable: &lt;br /&gt;
&lt;br /&gt;
  (lambda x:x**x)(4)  &lt;br /&gt;
&lt;br /&gt;
We can see that these two code snippets have the same results. It is more concise and flexible to define with lambda.&lt;br /&gt;
The above is a pure functional approach. In order to make code more state-less and concise, lambdas can be embedded inside the object-oriented language. The below code in Python demonstrates the use of lambda in a closure:&lt;br /&gt;
&lt;br /&gt;
  def fun(x):&lt;br /&gt;
    return x%3==0&lt;br /&gt;
    str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
    filter(fun,str)&lt;br /&gt;
&lt;br /&gt;
The above code works to find numbers which are divisible by 3.&lt;br /&gt;
We can simplify the code by the use of lambda as following:&lt;br /&gt;
&lt;br /&gt;
  str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
  print filter(lambda x: x%3==0, str)&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
A number of programming languages support mixing of both functional and object-oriented code. Three of these (Scala, Ruby, and Conjure), are described in more detail below.&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky. It supports mixing functional and object-oriented code.&lt;br /&gt;
&lt;br /&gt;
==== Mixing Functional and Object-Oriented Code in Scala ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object-oriented and functional programming. How can this happen? The functional world advocates immutability, but the object-oriented world focuses on the state and how to change it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . A rough translation into Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as:&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks much simpler and less verbose. Even though the above example shows an immutable collection, scala also provides mutable collections and object types in the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So it's the best of both worlds. Another part of the functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
==== Implicits in Scala ====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. Since you are splitting open the class and adding/overriding methods (in)|(to) the class, this feature is often called [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching]. Because other libraries may depend on some methods which you changed, often this leads to unexpected behavior at runtime. However, Scala provides yet another feature called [http://en.wikipedia.org/wiki/Implicit_function implicits] which helps you do this better.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Ruby is another language that, like Scala, supports mixing functional and object-oriented code. It is a dynamically typed Object-Oriented Language which supports multiple programming paradigms, including functional, object-oriented, imperative and reflective. In Ruby, everything is an object, every bit of information and code can have its own properties and actions. However, Ruby’s blocks can be functional. A Ruby programmer can attach a closure to any method, which generates a functional block inside an object oriented code. A closure is a piece of code that can access the lexical environment of its definition [http://www.ruby-lang.org/en/ 11].&lt;br /&gt;
&lt;br /&gt;
==== Ruby Mixing Example ====&lt;br /&gt;
&lt;br /&gt;
Consider the following code snippet in Ruby which uses Object Oriented concepts like Classes and functional programming concepts like lambda.&lt;br /&gt;
&lt;br /&gt;
 class Multiply&lt;br /&gt;
   def initialize(n)&lt;br /&gt;
     @block = lambda {|a| n * a}&lt;br /&gt;
   end&lt;br /&gt;
   def mul(a)&lt;br /&gt;
     @block.call a&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 twoMultiplier = Multiply.new 2                     &lt;br /&gt;
 puts twoMultiplier.mul(6)&lt;br /&gt;
&lt;br /&gt;
Here,'''''@block''''' is a closure. When we call the class ''Multiply'' using '''''twoAdder = Multiply.new 2''''' ,the ''initialize'' method is called by passing the parameter 2. Here n=2 binds itself to the block. So @block will be 2*a, that is,the closure remembers the parameter with which the initialize method was called even after the initialize method exits.  &lt;br /&gt;
&lt;br /&gt;
This value is used when the block is called in the add method.  &lt;br /&gt;
Thus,'''''twoMultiplier.mul(6)''''' will return 2*6 = 12&lt;br /&gt;
&lt;br /&gt;
==== Functional Style Coding in Ruby Blocks ====&lt;br /&gt;
&lt;br /&gt;
Blocks are basically nameless functions which can be passed to a function and then that function can invoke the passed in nameless function. This is a common style called [http://en.wikipedia.org/wiki/Higher-order_function higher order functions] among languages that handle functions as first class objects. Basically blocks can be designed for loop abstraction and lets the user to design their own way of iterating the values, thereby hiding the implementation details. &lt;br /&gt;
For example, if we want to iterate backwards from the end to the beginning without revealing its internal implementations, we could implement the loop logic inside the block and pass it to a method or function.&lt;br /&gt;
&lt;br /&gt;
Here is a [http://www.ruby-lang.org/en/ Ruby] implementation of block:&lt;br /&gt;
 &lt;br /&gt;
 def printlist(array,&amp;amp;reverse)&lt;br /&gt;
    array.each do |element|&lt;br /&gt;
       puts &amp;quot;array element: #{element}&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
    reverse.call(array)   /* Here it prints the reverse implementation of list*/&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
 printlist([1,2,3,4,5,6]) { |array| &lt;br /&gt;
   array.reverse.each do |element| &lt;br /&gt;
     puts &amp;quot;array element: #{element}&amp;quot; &lt;br /&gt;
   end &lt;br /&gt;
 }&lt;br /&gt;
The statements between { } is a block and it gets called by &amp;lt;code&amp;gt;reverse.call(array)&amp;lt;/code&amp;gt;within the printlist method.&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 31]] is also a functional programming language, and it is a dialect of Lisp. It is not a pure functional language. Instead, it is a dynamically typed language. Just like Java it runs on JVM platform, but its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
(functions arguments...)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The function and its arguments are enclosed in paranthesis. It has features like immutable data structures, high-order functions, recursion, and easy and fast java interoperability. &lt;br /&gt;
&lt;br /&gt;
In Clojure's model, value calculation is purely functional. Values never change. New values are functions of old. But, logical identity is well supported via atomic references to values. The value of a reference (state of an identity) is always observable without coordination and freely shareable between threads.&lt;br /&gt;
When programs are constructed this way, functional value calculation is independent of identity-value association. This makes clojure easier to understand and test.&lt;br /&gt;
&lt;br /&gt;
====Example Using Functional Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
Consider the following functional programming example in Clojure-&lt;br /&gt;
 (defn make-adder [x]&lt;br /&gt;
   (let [y x]&lt;br /&gt;
     (fn [z] (+ y z))))&lt;br /&gt;
 (def add2 (make-adder 2))&lt;br /&gt;
 (add2 4)&lt;br /&gt;
&lt;br /&gt;
Here,'''''defn make-adder [x]''''' defines a function called ''make-adder''.'''''let [y x]''''' gives a local name y for the value x. Since the scope of any local names is lexical, a function created in the scope of local names will close over their values.'''''fn [z] (+ y z)''''' does the addition of y and z.&lt;br /&gt;
''&lt;br /&gt;
'''def add2 (make-adder 2)''''' calls the function ''make-adder'' passing the parameter 2 and calls this as ''add2''.Now, ''add2'' has computed 2+z. When '''''add2 4''''' is called it computes 2+4=6&lt;br /&gt;
&lt;br /&gt;
====Example Using Object-Oriented Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
The following program implements Run-Time Polymorphism which is an object-oriented programming concept.&lt;br /&gt;
 (defmulti encounter (fn [x y] [(:Species x) (:Species y)]))&lt;br /&gt;
 (defmethod encounter [:Bunny :Lion] [b l] :run-away)&lt;br /&gt;
 (defmethod encounter [:Lion :Bunny] [l b] :eat)&lt;br /&gt;
 (defmethod encounter [:Lion :Lion] [l1 l2] :fight)&lt;br /&gt;
 (defmethod encounter [:Bunny :Bunny] [b1 b2] :mate)&lt;br /&gt;
 (def b1 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def b2 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def l1 {:Species :Lion :other :stuff})&lt;br /&gt;
 (def l2 {:Species :Lion :other :stuff})&lt;br /&gt;
 &lt;br /&gt;
 (encounter b1 l1)&lt;br /&gt;
 -&amp;gt; :run-away&lt;br /&gt;
 (encounter l1 l2)&lt;br /&gt;
 -&amp;gt; :fight&lt;br /&gt;
&lt;br /&gt;
Here,'''''defmulti''''' is used to define multiple methods which have the same method name '''''encounter'''''.Depending on the parameters passed to the encounter method, one of the four methods is called.&lt;br /&gt;
'''''def''''' defines each of the different species.&lt;br /&gt;
When, '''''(encounter b1 l1)''''' is called, the first ''encounter'' method is called with the parameters ''Bunny'' and ''Lion''. As a result, ''run-away'' is printed.&lt;br /&gt;
&lt;br /&gt;
=== Summary of Languages Supporting Mixing ===&lt;br /&gt;
&lt;br /&gt;
Each of the languages contains both functional and object-oriented features. The following table shows how each of the languages have both functional and object-oriented characterics. Not all characteristics of the languages are listed, but enough to demonstrate that the languages each have different ways of mixing object-oriented and functional techniques.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  &lt;br /&gt;
!  Functional Characteristics&lt;br /&gt;
!  Object-Oriented Characteristics&lt;br /&gt;
|-&lt;br /&gt;
! Scala&lt;br /&gt;
| Immutable objects, the ability to pass functions as parameters, implicits, closures.&lt;br /&gt;
| Every value is a object, mutable objects.&lt;br /&gt;
|-&lt;br /&gt;
! Ruby&lt;br /&gt;
| Functional programming used in blocks.&lt;br /&gt;
| Everything is an object.&lt;br /&gt;
|-&lt;br /&gt;
! Clojure&lt;br /&gt;
| Immutable data structures, high-order functions, recursion.&lt;br /&gt;
| Objects, runtime polymorphism, [http://en.wikipedia.org/wiki/Multiple_dispatch multimethods.]&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Functional_programming Wikipedia - Functional Programming]&lt;br /&gt;
#[http://www.cs.cornell.edu/riccardo/prog-smlnj/notes-011001.pdf Notes on programming Standard ML of New Jersey]&lt;br /&gt;
#[http://users.dickinson.edu/~braught/courses/cs132f01/classes/code/Factorial.src.html Introduction to Computing - Dickinson College]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Object-oriented_programming Wikipedia - Object Oriented Programming]&lt;br /&gt;
#[http://searchsoa.techtarget.com/sDefinition/0,,sid26_gci212681,00.html  More on Object Oriented Programming]&lt;br /&gt;
#[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas Understanding Ruby Blocks, Procs and Lambdas - Robert Sosinski]&lt;br /&gt;
#[http://www.codingday.com/power-of-functional-programming-its-features-and-its-future/ Power of Functional Programming, its Features and its Future]&lt;br /&gt;
#[http://skillsmatter.com/podcast/open-source-dot-net/mike-wagg-mark-needham-functional-and-oo-approaches-to-c-sharp-programming Mixing Functional and Object Oriented Approaches to Programming in C#]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigm]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Recursion Recursion]&lt;br /&gt;
#[http://www.scala-lang.org/ Scala]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Scala_%28programming_language%29 Scala Wikipedia]&lt;br /&gt;
#[http://clojure.org/ Clojure]&lt;br /&gt;
#[http://www.ruby-lang.org/en/ Ruby]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Standard_ML Standard ML]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Haskell_%28programming_language%29 Haskell]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/ML_%28programming_language%29 ML Family]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/C%2B%2B C++ Programming Language]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Visual_Basic_.NET Visual Basic .Net]&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;br /&gt;
#O'Reilly (2009), &amp;quot;Programming Scala&amp;quot;, ''O'Reilly Media Inc.''.&lt;br /&gt;
#Dave Thomas, Chad Fowler, Andy Hunt (2006) ''Programming Ruby'', The Pragmatic Bookshelf.&lt;br /&gt;
#[http://lamp.epfl.ch/~phaller/doc/haller10-Translucent_functions.pdf Philipp Halle, Lightweight language support for type-based, concurrent event processing, Lausanne, Switzerland, April 2010.]&lt;br /&gt;
#[http://biblion.epfl.ch/EPFL/theses/2007/3899/EPFL_TH3899.pdf Burak Emir, Object-Oriented Pattern Matching, EPFL, October 2007].&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63486</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63486"/>
		<updated>2012-09-11T01:48:23Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and data is immutable****. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily. &lt;br /&gt;
&lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-oriented Programming =&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm organized around interacting &amp;quot;objects&amp;quot;(usually instances of a class) rather than &amp;quot;actions&amp;quot; and data rather than logic. A basic principle of OOP is that a program consists of a list of subroutines which can perform individually. &lt;br /&gt;
&lt;br /&gt;
An object-oriented programming language provides support for the following object-oriented concepts--object, class, interface and inheritance. To illustrate this idea clearly and vividly let's review the following example-- your limbs. The &amp;quot;Limbs&amp;quot; is a class. Your body has two objects of type &amp;quot;limbs&amp;quot;, named arms and legs. Their main functions are controlled/ managed by a set of biological signals sent from central nervous system( through an interface). So the nervous system is an interface which your body uses to interact with your limbs. The &amp;quot;limbs&amp;quot; is a well architected class. The &amp;quot;legs&amp;quot; has a subclass which contains &amp;quot;left leg&amp;quot; and &amp;quot;Right leg&amp;quot;. The &amp;quot;legs&amp;quot; is being re-used to create the left leg and right leg by slightly changing the properties of it. If the &amp;quot;legs&amp;quot; owns attributes like length, color of skin etc, then the subclass, which contains &amp;quot;left leg&amp;quot; and &amp;quot;right leg&amp;quot; in this case, automatically inherit these attributes( that is called inheritance).&lt;br /&gt;
&lt;br /&gt;
We could code in object-oriented paradigm as:&lt;br /&gt;
&lt;br /&gt;
  class Limbs  /*define a class of limbs*/&lt;br /&gt;
    def initialize(limbs,length,colorofskin)&lt;br /&gt;
    @limbs=limbs&lt;br /&gt;
    @length=length&lt;br /&gt;
    @colorofskin=colorofskin&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  limbs=Limbs.new(&amp;quot;legs&amp;quot;,&amp;quot;100cm&amp;quot;,&amp;quot;white&amp;quot;)  /*create a new object in class &amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
  class Legs&amp;lt;Limbs   /*create a subclass &amp;quot;Legs&amp;quot;,which belong to class&amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
    def initialize(legs,length,colorofskin)&lt;br /&gt;
      super(length,colorofskin)&lt;br /&gt;
      @legs=legs&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
  legs=legs.new(&amp;quot;left leg&amp;quot;) /*create a new object in class of &amp;quot;Legs&amp;quot;*/&lt;br /&gt;
&lt;br /&gt;
== Features of Object-oriented Programming ==&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]. A programmer can simply create a new object that inherits many of its features from super-class. And also, they can overwrite existing operations or add new ones.This makes object-oriented programs easier to modify.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation].This refers to hiding the internal representation of the object from the outside view. You can hide unnecessary implementation details from the object user. One of the benefits of encapsulation is data protection.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism].This allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Consider the operator '+', for numbers it will generate the sum, but for strings it will produce a third string which concatenates the input strings.&lt;br /&gt;
&lt;br /&gt;
== Advantages of Object-oriented Programming ==&lt;br /&gt;
* Simplicity: we use software objects to simulate real world objects, so the complexity is reduced and the program structure is very clear.&lt;br /&gt;
* Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.&lt;br /&gt;
* Modifiability: programmers can easily make minor changes in the data representation or operations in an OOP. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.&lt;br /&gt;
* Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.&lt;br /&gt;
* Maintainability: objects can be maintained separately, making locating and fixing problems easier.&lt;br /&gt;
* Re-usability: objects can be reused in different programs.&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
In object-oriented world, data and operations are grouped together into modular units called objects and we combine objects into structured networks to form a program. The results are depend on arguments and objects' state at method invocation time. While in functional world, the basic elements are variables in the mathematical sense and functions in the mathematical sense. Functional programming can reduce side-effects. If there is no side-effects, it means your can apply the function at anywhere freely. No matter how you apply this function, the same input arguments produce the same results.&lt;br /&gt;
&lt;br /&gt;
According to above-mentioned information, we can perform functional programming on an object-oriented programming language because:&lt;br /&gt;
1). object can have constant state &lt;br /&gt;
2). method can depend only on its arguments and context available at method definition time&lt;br /&gt;
&lt;br /&gt;
Combining both these paradigms not only provide us a robust design structure, but also enable the programmers to develop solutions to complex problems quickly and effectively. One of the cornerstone of mixing functional and object-oriented code is treating functions as objects.It means that we can pass functions as arguments, store it and return them from other functions. This is highly useful in an user interface code where it can be used as call back functions which gets called when an event occurs(event driven programming).&lt;br /&gt;
&lt;br /&gt;
Some of the basic features of Functional Programming which can be combined with Object Oriented paradigm are:&lt;br /&gt;
&lt;br /&gt;
* Lambda Calculus&lt;br /&gt;
* Currying&lt;br /&gt;
* Powerful pattern matching&lt;br /&gt;
&lt;br /&gt;
Let us now understand how each of the above feature of Functional language fits in the Object Oriented paradigm.&lt;br /&gt;
&lt;br /&gt;
=== Lambda Calculus ===&lt;br /&gt;
Lambda calculus is the most critical basis of functional programming. A lambda expression is an anonymous expression that contain expressions and statements.Each expression stands for a function with one parameter. &lt;br /&gt;
&lt;br /&gt;
Let consider the following function:&lt;br /&gt;
&lt;br /&gt;
  def f(x)&lt;br /&gt;
  return x**2 &lt;br /&gt;
  print f(4)&lt;br /&gt;
&lt;br /&gt;
We can use a lambda calculus to compute this expression without assigning it to a variable: &lt;br /&gt;
&lt;br /&gt;
  (lambda x:x**x)(4)  &lt;br /&gt;
&lt;br /&gt;
We can see that these two code snippets have the same results. It is more concise and flexible to define with lambda.&lt;br /&gt;
The above is a pure functional approach. In order to make code more state-less and concise, lambdas can be embedded inside the object-oriented language. The below code in Python demonstrates the use of lambda in a closure:&lt;br /&gt;
&lt;br /&gt;
  def fun(x):&lt;br /&gt;
    return x%3==0&lt;br /&gt;
    str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
    filter(fun,str)&lt;br /&gt;
&lt;br /&gt;
The above code works to find numbers which are divisible by 3.&lt;br /&gt;
We can simplify the code by the use of lambda as following:&lt;br /&gt;
&lt;br /&gt;
  str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
  print filter(lambda x: x%3==0, str)&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
A number of programming languages support mixing of both functional and object-oriented code. Three of these (Scala, Ruby, and Conjure), are described in more detail below.&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky. It supports mixing functional and object-oriented code.&lt;br /&gt;
&lt;br /&gt;
==== Mixing Functional and Object-Oriented Code in Scala ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object-oriented and functional programming. How can this happen? The functional world advocates immutability, but the object-oriented world focuses on the state and how to change it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . A rough translation into Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as:&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks much simpler and less verbose. Even though the above example shows an immutable collection, scala also provides mutable collections and object types in the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So it's the best of both worlds. Another part of the functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
==== Implicits in Scala ====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. This feature is often called as [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching] because you are splitting open the class and adding/overriding methods (in)|(to) the class. Because other libraries may depend on some methods which you changed, often this leads to unexpected behavior at runtime. However, Scala provides yet another feature called [http://en.wikipedia.org/wiki/Implicit_function implicits] which helps you do this better.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Ruby is another language that, like Scala, supports mixing functional and object-oriented code. It is a dynamically typed Object-Oriented Language which supports multiple programming paradigms, including functional, object-oriented, imperative and reflective. In Ruby, everything is an object, every bit of information and code can have its own properties and actions. However, Ruby’s blocks can be functional. A Ruby programmer can attach a closure to any method, which generates a functional block inside an object oriented code. A closure is a piece of code that can access the lexical environment of its definition [http://www.ruby-lang.org/en/ 11].&lt;br /&gt;
&lt;br /&gt;
==== Ruby Mixing Example ====&lt;br /&gt;
&lt;br /&gt;
Consider the following code snippet in Ruby which uses Object Oriented concepts like Classes and functional programming concepts like lambda.&lt;br /&gt;
&lt;br /&gt;
 class Multiply&lt;br /&gt;
   def initialize(n)&lt;br /&gt;
     @block = lambda {|a| n * a}&lt;br /&gt;
   end&lt;br /&gt;
   def mul(a)&lt;br /&gt;
     @block.call a&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 twoMultiplier = Multiply.new 2                     &lt;br /&gt;
 puts twoMultiplier.mul(6)&lt;br /&gt;
&lt;br /&gt;
Here,'''''@block''''' is a closure. When we call the class ''Multiply'' using '''''twoAdder = Multiply.new 2''''' ,the ''initialize'' method is called by passing the parameter 2. Here n=2 binds itself to the block. So @block will be 2*a, that is,the closure remembers the parameter with which the initialize method was called even after the initialize method exits.  &lt;br /&gt;
&lt;br /&gt;
This value is used when the block is called in the add method.  &lt;br /&gt;
Thus,'''''twoMultiplier.mul(6)''''' will return 2*6 = 12&lt;br /&gt;
&lt;br /&gt;
==== Functional Style Coding in Ruby Blocks ====&lt;br /&gt;
&lt;br /&gt;
Blocks are basically nameless functions which can be passed to a function and then that function can invoke the passed in nameless function. This is a common style called [http://en.wikipedia.org/wiki/Higher-order_function higher order functions] among languages that handle functions as first class objects. Basically blocks can be designed for loop abstraction and lets the user to design their own way of iterating the values, thereby hiding the implementation details. &lt;br /&gt;
For example, if we want to iterate backwards from the end to the beginning without revealing its internal implementations, we could implement the loop logic inside the block and pass it to a method or function.&lt;br /&gt;
&lt;br /&gt;
Here is a [http://www.ruby-lang.org/en/ Ruby] implementation of block:&lt;br /&gt;
 &lt;br /&gt;
 def printlist(array,&amp;amp;reverse)&lt;br /&gt;
    array.each do |element|&lt;br /&gt;
       puts &amp;quot;array element: #{element}&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
    reverse.call(array)   /* Here it prints the reverse implementation of list*/&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
 printlist([1,2,3,4,5,6]) { |array| &lt;br /&gt;
   array.reverse.each do |element| &lt;br /&gt;
     puts &amp;quot;array element: #{element}&amp;quot; &lt;br /&gt;
   end &lt;br /&gt;
 }&lt;br /&gt;
The statements between { } is a block and it gets called by &amp;lt;code&amp;gt;reverse.call(array)&amp;lt;/code&amp;gt;within the printlist method.&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 31]] is also a functional programming language, and it is a dialect of Lisp. It is not a pure functional language. Instead, it is a dynamically typed language. Just like Java it runs on JVM platform, but its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
(functions arguments...)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The function and its arguments are enclosed in paranthesis. It has features like immutable data structures, high-order functions, recursion, and easy and fast java interoperability. &lt;br /&gt;
&lt;br /&gt;
In Clojure's model, value calculation is purely functional. Values never change. New values are functions of old. But, logical identity is well supported via atomic references to values. The value of a reference (state of an identity) is always observable without coordination and freely shareable between threads.&lt;br /&gt;
When programs are constructed this way, functional value calculation is independent of identity-value association. This makes clojure easier to understand and test.&lt;br /&gt;
&lt;br /&gt;
====Example Using Functional Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
Consider the following functional programming example in Clojure-&lt;br /&gt;
 (defn make-adder [x]&lt;br /&gt;
   (let [y x]&lt;br /&gt;
     (fn [z] (+ y z))))&lt;br /&gt;
 (def add2 (make-adder 2))&lt;br /&gt;
 (add2 4)&lt;br /&gt;
&lt;br /&gt;
Here,'''''defn make-adder [x]''''' defines a function called ''make-adder''.'''''let [y x]''''' gives a local name y for the value x. Since the scope of any local names is lexical, a function created in the scope of local names will close over their values.'''''fn [z] (+ y z)''''' does the addition of y and z.&lt;br /&gt;
''&lt;br /&gt;
'''def add2 (make-adder 2)''''' calls the function ''make-adder'' passing the parameter 2 and calls this as ''add2''.Now, ''add2'' has computed 2+z. When '''''add2 4''''' is called it computes 2+4=6&lt;br /&gt;
&lt;br /&gt;
====Example Using Object-Oriented Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
The following program implements Run-Time Polymorphism which is an object-oriented programming concept.&lt;br /&gt;
 (defmulti encounter (fn [x y] [(:Species x) (:Species y)]))&lt;br /&gt;
 (defmethod encounter [:Bunny :Lion] [b l] :run-away)&lt;br /&gt;
 (defmethod encounter [:Lion :Bunny] [l b] :eat)&lt;br /&gt;
 (defmethod encounter [:Lion :Lion] [l1 l2] :fight)&lt;br /&gt;
 (defmethod encounter [:Bunny :Bunny] [b1 b2] :mate)&lt;br /&gt;
 (def b1 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def b2 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def l1 {:Species :Lion :other :stuff})&lt;br /&gt;
 (def l2 {:Species :Lion :other :stuff})&lt;br /&gt;
 &lt;br /&gt;
 (encounter b1 l1)&lt;br /&gt;
 -&amp;gt; :run-away&lt;br /&gt;
 (encounter l1 l2)&lt;br /&gt;
 -&amp;gt; :fight&lt;br /&gt;
&lt;br /&gt;
Here,'''''defmulti''''' is used to define multiple methods which have the same method name '''''encounter'''''.Depending on the parameters passed to the encounter method, one of the four methods is called.&lt;br /&gt;
'''''def''''' defines each of the different species.&lt;br /&gt;
When, '''''(encounter b1 l1)''''' is called, the first ''encounter'' method is called with the parameters ''Bunny'' and ''Lion''. As a result, ''run-away'' is printed.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Functional_programming Wikipedia - Functional Programming]&lt;br /&gt;
#[http://www.cs.cornell.edu/riccardo/prog-smlnj/notes-011001.pdf Notes on programming Standard ML of New Jersey]&lt;br /&gt;
#[http://users.dickinson.edu/~braught/courses/cs132f01/classes/code/Factorial.src.html Introduction to Computing - Dickinson College]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Object-oriented_programming Wikipedia - Object Oriented Programming]&lt;br /&gt;
#[http://searchsoa.techtarget.com/sDefinition/0,,sid26_gci212681,00.html  More on Object Oriented Programming]&lt;br /&gt;
#[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas Understanding Ruby Blocks, Procs and Lambdas - Robert Sosinski]&lt;br /&gt;
#[http://www.codingday.com/power-of-functional-programming-its-features-and-its-future/ Power of Functional Programming, its Features and its Future]&lt;br /&gt;
#[http://skillsmatter.com/podcast/open-source-dot-net/mike-wagg-mark-needham-functional-and-oo-approaches-to-c-sharp-programming Mixing Functional and Object Oriented Approaches to Programming in C#]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigm]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Recursion Recursion]&lt;br /&gt;
#[http://www.scala-lang.org/ Scala]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Scala_%28programming_language%29 Scala Wikipedia]&lt;br /&gt;
#[http://clojure.org/ Clojure]&lt;br /&gt;
#[http://www.ruby-lang.org/en/ Ruby]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Standard_ML Standard ML]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Haskell_%28programming_language%29 Haskell]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/ML_%28programming_language%29 ML Family]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/C%2B%2B C++ Programming Language]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Visual_Basic_.NET Visual Basic .Net]&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;br /&gt;
#O'Reilly (2009), &amp;quot;Programming Scala&amp;quot;, ''O'Reilly Media Inc.''.&lt;br /&gt;
#Dave Thomas, Chad Fowler, Andy Hunt (2006) ''Programming Ruby'', The Pragmatic Bookshelf.&lt;br /&gt;
#[http://lamp.epfl.ch/~phaller/doc/haller10-Translucent_functions.pdf Philipp Halle, Lightweight language support for type-based, concurrent event processing, Lausanne, Switzerland, April 2010.]&lt;br /&gt;
#[http://biblion.epfl.ch/EPFL/theses/2007/3899/EPFL_TH3899.pdf Burak Emir, Object-Oriented Pattern Matching, EPFL, October 2007].&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63481</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63481"/>
		<updated>2012-09-11T01:45:50Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and data is immutable****. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily. &lt;br /&gt;
&lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-oriented Programming =&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm organized around interacting &amp;quot;objects&amp;quot;(usually instances of a class) rather than &amp;quot;actions&amp;quot; and data rather than logic. A basic principle of OOP is that a program consists of a list of subroutines which can perform individually. &lt;br /&gt;
&lt;br /&gt;
An object-oriented programming language provides support for the following object-oriented concepts--object, class, interface and inheritance. To illustrate this idea clearly and vividly let's review the following example-- your limbs. The &amp;quot;Limbs&amp;quot; is a class. Your body has two objects of type &amp;quot;limbs&amp;quot;, named arms and legs. Their main functions are controlled/ managed by a set of biological signals sent from central nervous system( through an interface). So the nervous system is an interface which your body uses to interact with your limbs. The &amp;quot;limbs&amp;quot; is a well architected class. The &amp;quot;legs&amp;quot; has a subclass which contains &amp;quot;left leg&amp;quot; and &amp;quot;Right leg&amp;quot;. The &amp;quot;legs&amp;quot; is being re-used to create the left leg and right leg by slightly changing the properties of it. If the &amp;quot;legs&amp;quot; owns attributes like length, color of skin etc, then the subclass, which contains &amp;quot;left leg&amp;quot; and &amp;quot;right leg&amp;quot; in this case, automatically inherit these attributes( that is called inheritance).&lt;br /&gt;
&lt;br /&gt;
We could code in object-oriented paradigm as:&lt;br /&gt;
&lt;br /&gt;
  class Limbs  /*define a class of limbs*/&lt;br /&gt;
    def initialize(limbs,length,colorofskin)&lt;br /&gt;
    @limbs=limbs&lt;br /&gt;
    @length=length&lt;br /&gt;
    @colorofskin=colorofskin&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  limbs=Limbs.new(&amp;quot;legs&amp;quot;,&amp;quot;100cm&amp;quot;,&amp;quot;white&amp;quot;)  /*create a new object in class &amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
  class Legs&amp;lt;Limbs   /*create a subclass &amp;quot;Legs&amp;quot;,which belong to class&amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
    def initialize(legs,length,colorofskin)&lt;br /&gt;
      super(length,colorofskin)&lt;br /&gt;
      @legs=legs&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
  legs=legs.new(&amp;quot;left leg&amp;quot;) /*create a new object in class of &amp;quot;Legs&amp;quot;*/&lt;br /&gt;
&lt;br /&gt;
== Features of Object-oriented Programming ==&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]. A programmer can simply create a new object that inherits many of its features from super-class. And also, they can overwrite existing operations or add new ones.This makes object-oriented programs easier to modify.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation].This refers to hiding the internal representation of the object from the outside view. You can hide unnecessary implementation details from the object user. One of the benefits of encapsulation is data protection.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism].This allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Consider the operator '+', for numbers it will generate the sum, but for strings it will produce a third string which concatenates the input strings.&lt;br /&gt;
&lt;br /&gt;
== Advantages of Object-oriented Programming ==&lt;br /&gt;
* Simplicity: we use software objects to simulate real world objects, so the complexity is reduced and the program structure is very clear.&lt;br /&gt;
* Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.&lt;br /&gt;
* Modifiability: programmers can easily make minor changes in the data representation or operations in an OOP. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.&lt;br /&gt;
* Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.&lt;br /&gt;
* Maintainability: objects can be maintained separately, making locating and fixing problems easier.&lt;br /&gt;
* Re-usability: objects can be reused in different programs.&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
In object-oriented world, data and operations are grouped together into modular units called objects and we combine objects into structured networks to form a program. The results are depend on arguments and objects' state at method invocation time. While in functional world, the basic elements are variables in the mathematical sense and functions in the mathematical sense. Functional programming can reduce side-effects. If there is no side-effects, it means your can apply the function at anywhere freely. No matter how you apply this function, the same input arguments produce the same results.&lt;br /&gt;
&lt;br /&gt;
According to above-mentioned information, we can perform functional programming on an object-oriented programming language because:&lt;br /&gt;
1). object can have constant state &lt;br /&gt;
2). method can depend only on its arguments and context available at method definition time&lt;br /&gt;
&lt;br /&gt;
Combining both these paradigms not only provide us a robust design structure, but also enable the programmers to develop solutions to complex problems quickly and effectively. One of the cornerstone of mixing functional and object-oriented code is treating functions as objects.It means that we can pass functions as arguments, store it and return them from other functions. This is highly useful in an user interface code where it can be used as call back functions which gets called when an event occurs(event driven programming).&lt;br /&gt;
&lt;br /&gt;
Some of the basic features of Functional Programming which can be combined with Object Oriented paradigm are:&lt;br /&gt;
&lt;br /&gt;
* Lambda Calculus&lt;br /&gt;
* Currying&lt;br /&gt;
* Powerful pattern matching&lt;br /&gt;
&lt;br /&gt;
Let us now understand how each of the above feature of Functional language fits in the Object Oriented paradigm.&lt;br /&gt;
&lt;br /&gt;
=== Lambda Calculus ===&lt;br /&gt;
Lambda calculus is the most critical basis of functional programming. A lambda expression is an anonymous expression that contain expressions and statements.Each expression stands for a function with one parameter. &lt;br /&gt;
&lt;br /&gt;
Let consider the following function:&lt;br /&gt;
&lt;br /&gt;
  def f(x)&lt;br /&gt;
  return x**2 &lt;br /&gt;
  print f(4)&lt;br /&gt;
&lt;br /&gt;
We can use a lambda calculus to compute this expression without assigning it to a variable: &lt;br /&gt;
&lt;br /&gt;
  (lambda x:x**x)(4)  &lt;br /&gt;
&lt;br /&gt;
We can see that these two code snippets have the same results. It is more concise and flexible to define with lambda.&lt;br /&gt;
The above is a pure functional approach. In order to make code more state-less and concise, lambdas can be embedded inside the object-oriented language. The below code in Python demonstrates the use of lambda in a closure:&lt;br /&gt;
&lt;br /&gt;
  def fun(x):&lt;br /&gt;
    return x%3==0&lt;br /&gt;
    str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
    filter(fun,str)&lt;br /&gt;
&lt;br /&gt;
The above code works to find numbers which are divisible by 3.&lt;br /&gt;
We can simplify the code by the use of lambda as following:&lt;br /&gt;
&lt;br /&gt;
  str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
  print filter(lambda x: x%3==0, str)&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
A number of programming languages support mixing of both functional and object-oriented code. Three of these (Scala, Ruby, and Conjure), are described in more detail below.&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky. It supports mixing functional and object-oriented code.&lt;br /&gt;
&lt;br /&gt;
==== Mixing Functional and Object-Oriented Code in Scala ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object-oriented and functional programming. How can this happen? The functional world advocates immutability, but the object-oriented world focuses on the state and how to change it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . A rough translation into Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as:&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks much simpler and less verbose. Even though the above example shows an immutable collection, scala also provides mutable collections and object types in the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So it's the best of both worlds. Another part of the functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
==== Implicits in Scala ====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. This feature is often called as [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching] because you are splitting open the class and adding/overriding methods (in)|(to) the class. Because other libraries may depend on some methods which you changed, often this leads to unexpected behavior at runtime. However, Scala provides yet another feature called [http://en.wikipedia.org/wiki/Implicit_function implicits] which helps you do this better.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Ruby is another language that, like Scala, supports mixing functional and object-oriented code. It is a dynamically typed Object-Oriented Language which supports multiple programming paradigms, including functional, object-oriented, imperative and reflective. In Ruby, everything is an object, every bit of information and code can have its own properties and actions. However, Ruby’s blocks can be functional. A Ruby programmer can attach a closure to any method, which generates a functional block inside an object oriented code. A closure is a piece of code that can access the lexical environment of its definition [http://www.ruby-lang.org/en/ 11].&lt;br /&gt;
&lt;br /&gt;
==== Ruby Mixing Example ====&lt;br /&gt;
&lt;br /&gt;
Consider the following code snippet in Ruby which uses Object Oriented concepts like Classes and functional programming concepts like lambda.&lt;br /&gt;
&lt;br /&gt;
 class Multiply&lt;br /&gt;
   def initialize(n)&lt;br /&gt;
     @block = lambda {|a| n * a}&lt;br /&gt;
   end&lt;br /&gt;
   def mul(a)&lt;br /&gt;
     @block.call a&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 twoMultiplier = Multiply.new 2                     &lt;br /&gt;
 puts twoMultiplier.mul(6)&lt;br /&gt;
&lt;br /&gt;
Here,'''''@block''''' is a closure. When we call the class ''Multiply'' using '''''twoAdder = Multiply.new 2''''' ,the ''initialize'' method is called by passing the parameter 2. Here n=2 binds itself to the block. So @block will be 2*a, that is,the closure remembers the parameter with which the initialize method was called even after the initialize method exits.  &lt;br /&gt;
&lt;br /&gt;
This value is used when the block is called in the add method.  &lt;br /&gt;
Thus,'''''twoMultiplier.mul(6)''''' will return 2*6 = 12&lt;br /&gt;
&lt;br /&gt;
==== Functional Style Coding in Ruby Blocks ====&lt;br /&gt;
&lt;br /&gt;
Blocks are basically nameless functions which can be passed to a function and then that function can invoke the passed in nameless function. This is a common style called [http://en.wikipedia.org/wiki/Higher-order_function higher order functions] among languages that handle functions as first class objects. Basically blocks can be designed for loop abstraction and lets the user to design their own way of iterating the values, thereby hiding the implementation details. &lt;br /&gt;
For example, if we want to iterate backwards from the end to the beginning without revealing its internal implementations, we could implement the loop logic inside the block and pass it to a method or function.&lt;br /&gt;
&lt;br /&gt;
Here is a [http://www.ruby-lang.org/en/ Ruby] implementation of block:&lt;br /&gt;
 &lt;br /&gt;
 def printlist(array,&amp;amp;reverse)&lt;br /&gt;
    array.each do |element|&lt;br /&gt;
       puts &amp;quot;array element: #{element}&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
    reverse.call(array)   /* Here it prints the reverse implementation of list*/&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
 printlist([1,2,3,4,5,6]) { |array| &lt;br /&gt;
   array.reverse.each do |element| &lt;br /&gt;
     puts &amp;quot;array element: #{element}&amp;quot; &lt;br /&gt;
   end &lt;br /&gt;
 }&lt;br /&gt;
The statements between { } is a block and it gets called by &amp;lt;code&amp;gt;reverse.call(array)&amp;lt;/code&amp;gt;within the printlist method.&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 31]] is also a functional programming language, and it is a dialect of Lisp. It is not a pure functional language. Instead, it is a dynamically typed language. Just like Java it runs on JVM platform, but its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
(functions arguments...)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The function and its arguments are enclosed in paranthesis. It has features like immutable data structures, high-order functions, recursion, and easy and fast java interoperability. &lt;br /&gt;
&lt;br /&gt;
In Clojure's model, value calculation is purely functional. Values never change. New values are functions of old. But, logical identity is well supported via atomic references to values. The value of a reference (state of an identity) is always observable without coordination and freely shareable between threads.&lt;br /&gt;
When programs are constructed this way, functional value calculation is independent of identity-value association. This makes clojure easier to understand and test.&lt;br /&gt;
&lt;br /&gt;
====Example Using Functional Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
Consider the following functional programming example in Clojure-&lt;br /&gt;
 (defn make-adder [x]&lt;br /&gt;
   (let [y x]&lt;br /&gt;
     (fn [z] (+ y z))))&lt;br /&gt;
 (def add2 (make-adder 2))&lt;br /&gt;
 (add2 4)&lt;br /&gt;
&lt;br /&gt;
Here,'''''defn make-adder [x]''''' defines a function called ''make-adder''.'''''let [y x]''''' gives a local name y for the value x. Since the scope of any local names is lexical, a function created in the scope of local names will close over their values.'''''fn [z] (+ y z)''''' does the addition of y and z.&lt;br /&gt;
''&lt;br /&gt;
'''def add2 (make-adder 2)''''' calls the function ''make-adder'' passing the parameter 2 and calls this as ''add2''.Now, ''add2'' has computed 2+z. When '''''add2 4''''' is called it computes 2+4=6&lt;br /&gt;
&lt;br /&gt;
====Example Using Object-Oriented Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
The following program implements Run-Time Polymorphism which is an object-oriented programming concept.&lt;br /&gt;
 (defmulti encounter (fn [x y] [(:Species x) (:Species y)]))&lt;br /&gt;
 (defmethod encounter [:Bunny :Lion] [b l] :run-away)&lt;br /&gt;
 (defmethod encounter [:Lion :Bunny] [l b] :eat)&lt;br /&gt;
 (defmethod encounter [:Lion :Lion] [l1 l2] :fight)&lt;br /&gt;
 (defmethod encounter [:Bunny :Bunny] [b1 b2] :mate)&lt;br /&gt;
 (def b1 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def b2 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def l1 {:Species :Lion :other :stuff})&lt;br /&gt;
 (def l2 {:Species :Lion :other :stuff})&lt;br /&gt;
 &lt;br /&gt;
 (encounter b1 l1)&lt;br /&gt;
 -&amp;gt; :run-away&lt;br /&gt;
 (encounter l1 l2)&lt;br /&gt;
 -&amp;gt; :fight&lt;br /&gt;
&lt;br /&gt;
Here,'''''defmulti''''' is used to define multiple methods which have the same method name '''''encounter'''''.Depending on the parameters passed to the encounter method, one of the four methods is called.&lt;br /&gt;
'''''def''''' defines each of the different species.&lt;br /&gt;
When, '''''(encounter b1 l1)''''' is called, the first ''encounter'' method is called with the parameters ''Bunny'' and ''Lion''. As a result, ''run-away'' is printed.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Functional_programming Wikipedia - Functional Programming]&lt;br /&gt;
#[http://www.cs.cornell.edu/riccardo/prog-smlnj/notes-011001.pdf Notes on programming Standard ML of New Jersey]&lt;br /&gt;
#[http://users.dickinson.edu/~braught/courses/cs132f01/classes/code/Factorial.src.html Introduction to Computing - Dickinson College]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Object-oriented_programming Wikipedia - Object Oriented Programming]&lt;br /&gt;
#[http://searchsoa.techtarget.com/sDefinition/0,,sid26_gci212681,00.html  More on Object Oriented Programming]&lt;br /&gt;
#[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas Understanding Ruby Blocks, Procs and Lambdas - Robert Sosinski]&lt;br /&gt;
#[http://www.codingday.com/power-of-functional-programming-its-features-and-its-future/ Power of Functional Programming, its Features and its Future]&lt;br /&gt;
#[http://skillsmatter.com/podcast/open-source-dot-net/mike-wagg-mark-needham-functional-and-oo-approaches-to-c-sharp-programming Mixing Functional and Object Oriented Approaches to Programming in C#]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigm]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Recursion Recursion]&lt;br /&gt;
#[http://www.scala-lang.org/ Scala]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Scala_%28programming_language%29 Scala Wikipedia]&lt;br /&gt;
#[http://clojure.org/ Clojure]&lt;br /&gt;
#[http://www.ruby-lang.org/en/ Ruby]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Standard_ML Standard ML]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Haskell_%28programming_language%29 Haskell]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/ML_%28programming_language%29 ML Family]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/C%2B%2B C++ Programming Language]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Visual_Basic_.NET Visual Basic .Net]&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63480</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63480"/>
		<updated>2012-09-11T01:39:02Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and data is immutable****. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily. &lt;br /&gt;
&lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-oriented Programming =&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm organized around interacting &amp;quot;objects&amp;quot;(usually instances of a class) rather than &amp;quot;actions&amp;quot; and data rather than logic. A basic principle of OOP is that a program consists of a list of subroutines which can perform individually. &lt;br /&gt;
&lt;br /&gt;
An object-oriented programming language provides support for the following object-oriented concepts--object, class, interface and inheritance. To illustrate this idea clearly and vividly let's review the following example-- your limbs. The &amp;quot;Limbs&amp;quot; is a class. Your body has two objects of type &amp;quot;limbs&amp;quot;, named arms and legs. Their main functions are controlled/ managed by a set of biological signals sent from central nervous system( through an interface). So the nervous system is an interface which your body uses to interact with your limbs. The &amp;quot;limbs&amp;quot; is a well architected class. The &amp;quot;legs&amp;quot; has a subclass which contains &amp;quot;left leg&amp;quot; and &amp;quot;Right leg&amp;quot;. The &amp;quot;legs&amp;quot; is being re-used to create the left leg and right leg by slightly changing the properties of it. If the &amp;quot;legs&amp;quot; owns attributes like length, color of skin etc, then the subclass, which contains &amp;quot;left leg&amp;quot; and &amp;quot;right leg&amp;quot; in this case, automatically inherit these attributes( that is called inheritance).&lt;br /&gt;
&lt;br /&gt;
We could code in object-oriented paradigm as:&lt;br /&gt;
&lt;br /&gt;
  class Limbs  /*define a class of limbs*/&lt;br /&gt;
    def initialize(limbs,length,colorofskin)&lt;br /&gt;
    @limbs=limbs&lt;br /&gt;
    @length=length&lt;br /&gt;
    @colorofskin=colorofskin&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  limbs=Limbs.new(&amp;quot;legs&amp;quot;,&amp;quot;100cm&amp;quot;,&amp;quot;white&amp;quot;)  /*create a new object in class &amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
  class Legs&amp;lt;Limbs   /*create a subclass &amp;quot;Legs&amp;quot;,which belong to class&amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
    def initialize(legs,length,colorofskin)&lt;br /&gt;
      super(length,colorofskin)&lt;br /&gt;
      @legs=legs&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
  legs=legs.new(&amp;quot;left leg&amp;quot;) /*create a new object in class of &amp;quot;Legs&amp;quot;*/&lt;br /&gt;
&lt;br /&gt;
== Features of Object-oriented Programming ==&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]. A programmer can simply create a new object that inherits many of its features from super-class. And also, they can overwrite existing operations or add new ones.This makes object-oriented programs easier to modify.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation].This refers to hiding the internal representation of the object from the outside view. You can hide unnecessary implementation details from the object user. One of the benefits of encapsulation is data protection.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism].This allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Consider the operator '+', for numbers it will generate the sum, but for strings it will produce a third string which concatenates the input strings.&lt;br /&gt;
&lt;br /&gt;
== Advantages of Object-oriented Programming ==&lt;br /&gt;
* Simplicity: we use software objects to simulate real world objects, so the complexity is reduced and the program structure is very clear.&lt;br /&gt;
* Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.&lt;br /&gt;
* Modifiability: programmers can easily make minor changes in the data representation or operations in an OOP. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.&lt;br /&gt;
* Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.&lt;br /&gt;
* Maintainability: objects can be maintained separately, making locating and fixing problems easier.&lt;br /&gt;
* Re-usability: objects can be reused in different programs.&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
In object-oriented world, data and operations are grouped together into modular units called objects and we combine objects into structured networks to form a program. The results are depend on arguments and objects' state at method invocation time. While in functional world, the basic elements are variables in the mathematical sense and functions in the mathematical sense. Functional programming can reduce side-effects. If there is no side-effects, it means your can apply the function at anywhere freely. No matter how you apply this function, the same input arguments produce the same results.&lt;br /&gt;
&lt;br /&gt;
According to above-mentioned information, we can perform functional programming on an object-oriented programming language because:&lt;br /&gt;
1). object can have constant state &lt;br /&gt;
2). method can depend only on its arguments and context available at method definition time&lt;br /&gt;
&lt;br /&gt;
Combining both these paradigms not only provide us a robust design structure, but also enable the programmers to develop solutions to complex problems quickly and effectively. One of the cornerstone of mixing functional and object-oriented code is treating functions as objects.It means that we can pass functions as arguments, store it and return them from other functions. This is highly useful in an user interface code where it can be used as call back functions which gets called when an event occurs(event driven programming).&lt;br /&gt;
&lt;br /&gt;
Some of the basic features of Functional Programming which can be combined with Object Oriented paradigm are:&lt;br /&gt;
&lt;br /&gt;
* Lambda Calculus&lt;br /&gt;
* Currying&lt;br /&gt;
* Powerful pattern matching&lt;br /&gt;
&lt;br /&gt;
Let us now understand how each of the above feature of Functional language fits in the Object Oriented paradigm.&lt;br /&gt;
&lt;br /&gt;
=== Lambda Calculus ===&lt;br /&gt;
Lambda calculus is the most critical basis of functional programming. A lambda expression is an anonymous expression that contain expressions and statements.Each expression stands for a function with one parameter. &lt;br /&gt;
&lt;br /&gt;
Let consider the following function:&lt;br /&gt;
&lt;br /&gt;
  def f(x)&lt;br /&gt;
  return x**2 &lt;br /&gt;
  print f(4)&lt;br /&gt;
&lt;br /&gt;
We can use a lambda calculus to compute this expression without assigning it to a variable: &lt;br /&gt;
&lt;br /&gt;
  (lambda x:x**x)(4)  &lt;br /&gt;
&lt;br /&gt;
We can see that these two code snippets have the same results. It is more concise and flexible to define with lambda.&lt;br /&gt;
The above is a pure functional approach. In order to make code more state-less and concise, lambdas can be embedded inside the object-oriented language. The below code in Python demonstrates the use of lambda in a closure:&lt;br /&gt;
&lt;br /&gt;
  def fun(x):&lt;br /&gt;
    return x%3==0&lt;br /&gt;
    str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
    filter(fun,str)&lt;br /&gt;
&lt;br /&gt;
The above code works to find numbers which are divisible by 3.&lt;br /&gt;
We can simplify the code by the use of lambda as following:&lt;br /&gt;
&lt;br /&gt;
  str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
  print filter(lambda x: x%3==0, str)&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
A number of programming languages support mixing of both functional and object-oriented code. Three of these (Scala, Ruby, and Conjure), are described in more detail below.&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky. It supports mixing functional and object-oriented code.&lt;br /&gt;
&lt;br /&gt;
==== Mixing Functional and Object-Oriented Code in Scala ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object-oriented and functional programming. How can this happen? The functional world advocates immutability, but the object-oriented world focuses on the state and how to change it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . A rough translation into Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as:&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks much simpler and less verbose. Even though the above example shows an immutable collection, scala also provides mutable collections and object types in the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So it's the best of both worlds. Another part of the functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
==== Implicits in Scala ====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. This feature is often called as [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching] because you are splitting open the class and adding/overriding methods (in)|(to) the class. Because other libraries may depend on some methods which you changed, often this leads to unexpected behavior at runtime. However, Scala provides yet another feature called [http://en.wikipedia.org/wiki/Implicit_function implicits] which helps you do this better.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Ruby is another language that, like Scala, supports mixing functional and object-oriented code. It is a dynamically typed Object-Oriented Language which supports multiple programming paradigms, including functional, object-oriented, imperative and reflective. In Ruby, everything is an object, every bit of information and code can have its own properties and actions. However, Ruby’s blocks can be functional. A Ruby programmer can attach a closure to any method, which generates a functional block inside an object oriented code. A closure is a piece of code that can access the lexical environment of its definition [http://www.ruby-lang.org/en/ 11].&lt;br /&gt;
&lt;br /&gt;
==== Ruby Mixing Example ====&lt;br /&gt;
&lt;br /&gt;
Consider the following code snippet in Ruby which uses Object Oriented concepts like Classes and functional programming concepts like lambda.&lt;br /&gt;
&lt;br /&gt;
 class Multiply&lt;br /&gt;
   def initialize(n)&lt;br /&gt;
     @block = lambda {|a| n * a}&lt;br /&gt;
   end&lt;br /&gt;
   def mul(a)&lt;br /&gt;
     @block.call a&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 twoMultiplier = Multiply.new 2                     &lt;br /&gt;
 puts twoMultiplier.mul(6)&lt;br /&gt;
&lt;br /&gt;
Here,'''''@block''''' is a closure. When we call the class ''Multiply'' using '''''twoAdder = Multiply.new 2''''' ,the ''initialize'' method is called by passing the parameter 2. Here n=2 binds itself to the block. So @block will be 2*a, that is,the closure remembers the parameter with which the initialize method was called even after the initialize method exits.  &lt;br /&gt;
&lt;br /&gt;
This value is used when the block is called in the add method.  &lt;br /&gt;
Thus,'''''twoMultiplier.mul(6)''''' will return 2*6 = 12&lt;br /&gt;
&lt;br /&gt;
==== Functional Style Coding in Ruby Blocks ====&lt;br /&gt;
&lt;br /&gt;
Blocks are basically nameless functions which can be passed to a function and then that function can invoke the passed in nameless function. This is a common style called [http://en.wikipedia.org/wiki/Higher-order_function higher order functions] among languages that handle functions as first class objects. Basically blocks can be designed for loop abstraction and lets the user to design their own way of iterating the values, thereby hiding the implementation details. &lt;br /&gt;
For example, if we want to iterate backwards from the end to the beginning without revealing its internal implementations, we could implement the loop logic inside the block and pass it to a method or function.&lt;br /&gt;
&lt;br /&gt;
Here is a [http://www.ruby-lang.org/en/ Ruby] implementation of block:&lt;br /&gt;
 &lt;br /&gt;
 def printlist(array,&amp;amp;reverse)&lt;br /&gt;
    array.each do |element|&lt;br /&gt;
       puts &amp;quot;array element: #{element}&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
    reverse.call(array)   /* Here it prints the reverse implementation of list*/&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
 printlist([1,2,3,4,5,6]) { |array| &lt;br /&gt;
   array.reverse.each do |element| &lt;br /&gt;
     puts &amp;quot;array element: #{element}&amp;quot; &lt;br /&gt;
   end &lt;br /&gt;
 }&lt;br /&gt;
The statements between { } is a block and it gets called by &amp;lt;code&amp;gt;reverse.call(array)&amp;lt;/code&amp;gt;within the printlist method.&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language, and it is a dialect of Lisp. It is not a pure functional language. Instead, it is a dynamically typed language. Just like Java it runs on JVM platform, but its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
(functions arguments...)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The function and its arguments are enclosed in paranthesis. It has features like immutable data structures, high-order functions, recursion, and easy and fast java interoperability. &lt;br /&gt;
&lt;br /&gt;
In Clojure's model, value calculation is purely functional. Values never change. New values are functions of old. But, logical identity is well supported via atomic references to values. The value of a reference (state of an identity) is always observable without coordination and freely shareable between threads.&lt;br /&gt;
When programs are constructed this way, functional value calculation is independent of identity-value association. This makes clojure easier to understand and test.&lt;br /&gt;
&lt;br /&gt;
====Example Using Functional Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
Consider the following functional programming example in Clojure-&lt;br /&gt;
 (defn make-adder [x]&lt;br /&gt;
   (let [y x]&lt;br /&gt;
     (fn [z] (+ y z))))&lt;br /&gt;
 (def add2 (make-adder 2))&lt;br /&gt;
 (add2 4)&lt;br /&gt;
&lt;br /&gt;
Here,'''''defn make-adder [x]''''' defines a function called ''make-adder''.'''''let [y x]''''' gives a local name y for the value x. Since the scope of any local names is lexical, a function created in the scope of local names will close over their values.'''''fn [z] (+ y z)''''' does the addition of y and z.&lt;br /&gt;
''&lt;br /&gt;
'''def add2 (make-adder 2)''''' calls the function ''make-adder'' passing the parameter 2 and calls this as ''add2''.Now, ''add2'' has computed 2+z. When '''''add2 4''''' is called it computes 2+4=6&lt;br /&gt;
&lt;br /&gt;
====Example Using Object-Oriented Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
The following program implements Run-Time Polymorphism which is an object-oriented programming concept.&lt;br /&gt;
 (defmulti encounter (fn [x y] [(:Species x) (:Species y)]))&lt;br /&gt;
 (defmethod encounter [:Bunny :Lion] [b l] :run-away)&lt;br /&gt;
 (defmethod encounter [:Lion :Bunny] [l b] :eat)&lt;br /&gt;
 (defmethod encounter [:Lion :Lion] [l1 l2] :fight)&lt;br /&gt;
 (defmethod encounter [:Bunny :Bunny] [b1 b2] :mate)&lt;br /&gt;
 (def b1 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def b2 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def l1 {:Species :Lion :other :stuff})&lt;br /&gt;
 (def l2 {:Species :Lion :other :stuff})&lt;br /&gt;
 &lt;br /&gt;
 (encounter b1 l1)&lt;br /&gt;
 -&amp;gt; :run-away&lt;br /&gt;
 (encounter l1 l2)&lt;br /&gt;
 -&amp;gt; :fight&lt;br /&gt;
&lt;br /&gt;
Here,'''''defmulti''''' is used to define multiple methods which have the same method name '''''encounter'''''.Depending on the parameters passed to the encounter method, one of the four methods is called.&lt;br /&gt;
'''''def''''' defines each of the different species.&lt;br /&gt;
When, '''''(encounter b1 l1)''''' is called, the first ''encounter'' method is called with the parameters ''Bunny'' and ''Lion''. As a result, ''run-away'' is printed.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Functional_programming Wikipedia - Functional Programming]&lt;br /&gt;
#[http://www.cs.cornell.edu/riccardo/prog-smlnj/notes-011001.pdf Notes on programming Standard ML of New Jersey]&lt;br /&gt;
#[http://users.dickinson.edu/~braught/courses/cs132f01/classes/code/Factorial.src.html Introduction to Computing - Dickinson College]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Object-oriented_programming Wikipedia - Object Oriented Programming]&lt;br /&gt;
#[http://searchsoa.techtarget.com/sDefinition/0,,sid26_gci212681,00.html  More on Object Oriented Programming]&lt;br /&gt;
#[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas Understanding Ruby Blocks, Procs and Lambdas - Robert Sosinski]&lt;br /&gt;
#[http://www.codingday.com/power-of-functional-programming-its-features-and-its-future/ Power of Functional Programming, its Features and its Future]&lt;br /&gt;
#[http://skillsmatter.com/podcast/open-source-dot-net/mike-wagg-mark-needham-functional-and-oo-approaches-to-c-sharp-programming Mixing Functional and Object Oriented Approaches to Programming in C#]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigm]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Recursion Recursion]&lt;br /&gt;
#[http://www.scala-lang.org/ Scala]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Scala_%28programming_language%29 Scala Wikipedia]&lt;br /&gt;
#[http://clojure.org/ Clojure]&lt;br /&gt;
#[http://www.ruby-lang.org/en/ Ruby]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Standard_ML Standard ML]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Haskell_%28programming_language%29 Haskell]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/ML_%28programming_language%29 ML Family]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/C%2B%2B C++ Programming Language]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Visual_Basic_.NET Visual Basic .Net]&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63479</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63479"/>
		<updated>2012-09-11T01:37:47Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and data is immutable****. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily. &lt;br /&gt;
&lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-oriented Programming =&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm organized around interacting &amp;quot;objects&amp;quot;(usually instances of a class) rather than &amp;quot;actions&amp;quot; and data rather than logic. A basic principle of OOP is that a program consists of a list of subroutines which can perform individually. &lt;br /&gt;
&lt;br /&gt;
An object-oriented programming language provides support for the following object-oriented concepts--object, class, interface and inheritance. To illustrate this idea clearly and vividly let's review the following example-- your limbs. The &amp;quot;Limbs&amp;quot; is a class. Your body has two objects of type &amp;quot;limbs&amp;quot;, named arms and legs. Their main functions are controlled/ managed by a set of biological signals sent from central nervous system( through an interface). So the nervous system is an interface which your body uses to interact with your limbs. The &amp;quot;limbs&amp;quot; is a well architected class. The &amp;quot;legs&amp;quot; has a subclass which contains &amp;quot;left leg&amp;quot; and &amp;quot;Right leg&amp;quot;. The &amp;quot;legs&amp;quot; is being re-used to create the left leg and right leg by slightly changing the properties of it. If the &amp;quot;legs&amp;quot; owns attributes like length, color of skin etc, then the subclass, which contains &amp;quot;left leg&amp;quot; and &amp;quot;right leg&amp;quot; in this case, automatically inherit these attributes( that is called inheritance).&lt;br /&gt;
&lt;br /&gt;
We could code in object-oriented paradigm as:&lt;br /&gt;
&lt;br /&gt;
  class Limbs  /*define a class of limbs*/&lt;br /&gt;
    def initialize(limbs,length,colorofskin)&lt;br /&gt;
    @limbs=limbs&lt;br /&gt;
    @length=length&lt;br /&gt;
    @colorofskin=colorofskin&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  limbs=Limbs.new(&amp;quot;legs&amp;quot;,&amp;quot;100cm&amp;quot;,&amp;quot;white&amp;quot;)  /*create a new object in class &amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
  class Legs&amp;lt;Limbs   /*create a subclass &amp;quot;Legs&amp;quot;,which belong to class&amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
    def initialize(legs,length,colorofskin)&lt;br /&gt;
      super(length,colorofskin)&lt;br /&gt;
      @legs=legs&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
  legs=legs.new(&amp;quot;left leg&amp;quot;) /*create a new object in class of &amp;quot;Legs&amp;quot;*/&lt;br /&gt;
&lt;br /&gt;
== Features of Object-oriented Programming ==&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]. A programmer can simply create a new object that inherits many of its features from super-class. And also, they can overwrite existing operations or add new ones.This makes object-oriented programs easier to modify.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation].This refers to hiding the internal representation of the object from the outside view. You can hide unnecessary implementation details from the object user. One of the benefits of encapsulation is data protection.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism].This allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Consider the operator '+', for numbers it will generate the sum, but for strings it will produce a third string which concatenates the input strings.&lt;br /&gt;
&lt;br /&gt;
== Advantages of Object-oriented Programming ==&lt;br /&gt;
* Simplicity: we use software objects to simulate real world objects, so the complexity is reduced and the program structure is very clear.&lt;br /&gt;
* Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.&lt;br /&gt;
* Modifiability: programmers can easily make minor changes in the data representation or operations in an OOP. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.&lt;br /&gt;
* Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.&lt;br /&gt;
* Maintainability: objects can be maintained separately, making locating and fixing problems easier.&lt;br /&gt;
* Re-usability: objects can be reused in different programs.&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
In object-oriented world, data and operations are grouped together into modular units called objects and we combine objects into structured networks to form a program. The results are depend on arguments and objects' state at method invocation time. While in functional world, the basic elements are variables in the mathematical sense and functions in the mathematical sense. Functional programming can reduce side-effects. If there is no side-effects, it means your can apply the function at anywhere freely. No matter how you apply this function, the same input arguments produce the same results.&lt;br /&gt;
&lt;br /&gt;
According to above-mentioned information, we can perform functional programming on an object-oriented programming language because:&lt;br /&gt;
1). object can have constant state &lt;br /&gt;
2). method can depend only on its arguments and context available at method definition time&lt;br /&gt;
&lt;br /&gt;
Combining both these paradigms not only provide us a robust design structure, but also enable the programmers to develop solutions to complex problems quickly and effectively. One of the cornerstone of mixing functional and object-oriented code is treating functions as objects.It means that we can pass functions as arguments, store it and return them from other functions. This is highly useful in an user interface code where it can be used as call back functions which gets called when an event occurs(event driven programming).&lt;br /&gt;
&lt;br /&gt;
Some of the basic features of Functional Programming which can be combined with Object Oriented paradigm are:&lt;br /&gt;
&lt;br /&gt;
* Lambda Calculus&lt;br /&gt;
* Currying&lt;br /&gt;
* Powerful pattern matching&lt;br /&gt;
&lt;br /&gt;
Let us now understand how each of the above feature of Functional language fits in the Object Oriented paradigm.&lt;br /&gt;
&lt;br /&gt;
=== Lambda Calculus ===&lt;br /&gt;
Lambda calculus is the most critical basis of functional programming. A lambda expression is an anonymous expression that contain expressions and statements.Each expression stands for a function with one parameter. &lt;br /&gt;
&lt;br /&gt;
Let consider the following function:&lt;br /&gt;
&lt;br /&gt;
  def f(x)&lt;br /&gt;
  return x**2 &lt;br /&gt;
  print f(4)&lt;br /&gt;
&lt;br /&gt;
We can use a lambda calculus to compute this expression without assigning it to a variable: &lt;br /&gt;
&lt;br /&gt;
  (lambda x:x**x)(4)  &lt;br /&gt;
&lt;br /&gt;
We can see that these two code snippets have the same results. It is more concise and flexible to define with lambda.&lt;br /&gt;
The above is a pure functional approach. In order to make code more state-less and concise, lambdas can be embedded inside the object-oriented language. The below code in Python demonstrates the use of lambda in a closure:&lt;br /&gt;
&lt;br /&gt;
  def fun(x):&lt;br /&gt;
    return x%3==0&lt;br /&gt;
    str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
    filter(fun,str)&lt;br /&gt;
&lt;br /&gt;
The above code works to find numbers which are divisible by 3.&lt;br /&gt;
We can simplify the code by the use of lambda as following:&lt;br /&gt;
&lt;br /&gt;
  str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
  print filter(lambda x: x%3==0, str)&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
A number of programming languages support mixing of both functional and object-oriented code. Three of these (Scala, Ruby, and Conjure), are described in more detail below.&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky. It supports mixing functional and object-oriented code.&lt;br /&gt;
&lt;br /&gt;
==== Mixing Functional and Object-Oriented Code in Scala ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object-oriented and functional programming. How can this happen? The functional world advocates immutability, but the object-oriented world focuses on the state and how to change it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . A rough translation into Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as:&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks much simpler and less verbose. Even though the above example shows an immutable collection, scala also provides mutable collections and object types in the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So it's the best of both worlds. Another part of the functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
==== Implicits in Scala ====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. This feature is often called as [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching] because you are splitting open the class and adding/overriding methods (in)|(to) the class. Because other libraries may depend on some methods which you changed, often this leads to unexpected behavior at runtime. However, Scala provides yet another feature called [http://en.wikipedia.org/wiki/Implicit_function implicits] which helps you do this better.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Ruby is another language that, like Scala, supports mixing functional and object-oriented code. It is a dynamically typed Object-Oriented Language which supports multiple programming paradigms, including functional, object-oriented, imperative and reflective. In Ruby, everything is an object, every bit of information and code can have its own properties and actions. However, Ruby’s blocks can be functional. A Ruby programmer can attach a closure to any method, which generates a functional block inside an object oriented code. A closure is a piece of code that can access the lexical environment of its definition [http://www.ruby-lang.org/en/ 11].&lt;br /&gt;
&lt;br /&gt;
==== Ruby Mixing Example ====&lt;br /&gt;
&lt;br /&gt;
Consider the following code snippet in Ruby which uses Object Oriented concepts like Classes and functional programming concepts like lambda.&lt;br /&gt;
&lt;br /&gt;
 class Multiply&lt;br /&gt;
   def initialize(n)&lt;br /&gt;
     @block = lambda {|a| n * a}&lt;br /&gt;
   end&lt;br /&gt;
   def mul(a)&lt;br /&gt;
     @block.call a&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 twoMultiplier = Multiply.new 2                     &lt;br /&gt;
 puts twoMultiplier.mul(6)&lt;br /&gt;
&lt;br /&gt;
Here,'''''@block''''' is a closure. When we call the class ''Multiply'' using '''''twoAdder = Multiply.new 2''''' ,the ''initialize'' method is called by passing the parameter 2. Here n=2 binds itself to the block. So @block will be 2*a, that is,the closure remembers the parameter with which the initialize method was called even after the initialize method exits.  &lt;br /&gt;
&lt;br /&gt;
This value is used when the block is called in the add method.  &lt;br /&gt;
Thus,'''''twoMultiplier.mul(6)''''' will return 2*6 = 12&lt;br /&gt;
&lt;br /&gt;
==== Functional Style Coding in Ruby Blocks ====&lt;br /&gt;
&lt;br /&gt;
Blocks are basically nameless functions which can be passed to a function and then that function can invoke the passed in nameless function. This is a common style called [http://en.wikipedia.org/wiki/Higher-order_function higher order functions] among languages that handle functions as first class objects. Basically blocks can be designed for loop abstraction and lets the user to design their own way of iterating the values, thereby hiding the implementation details. &lt;br /&gt;
For example, if we want to iterate backwards from the end to the beginning without revealing its internal implementations, we could implement the loop logic inside the block and pass it to a method or function.&lt;br /&gt;
&lt;br /&gt;
Here is a [http://www.ruby-lang.org/en/ Ruby] implementation of block:&lt;br /&gt;
 &lt;br /&gt;
 def printlist(array,&amp;amp;reverse)&lt;br /&gt;
    array.each do |element|&lt;br /&gt;
       puts &amp;quot;array element: #{element}&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
    reverse.call(array)   /* Here it prints the reverse implementation of list*/&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
 printlist([1,2,3,4,5,6]) { |array| &lt;br /&gt;
   array.reverse.each do |element| &lt;br /&gt;
     puts &amp;quot;array element: #{element}&amp;quot; &lt;br /&gt;
   end &lt;br /&gt;
 }&lt;br /&gt;
The statements between { } is a block and it gets called by &amp;lt;code&amp;gt;reverse.call(array)&amp;lt;/code&amp;gt;within the printlist method.&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language, and it is a dialect of Lisp. It is not a pure functional language. Instead, it is a dynamically typed language. Just like Java it runs on JVM platform, but its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
(functions arguments...)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The function and its arguments are enclosed in paranthesis. It has features like immutable data structures, high-order functions, recursion, and easy and fast java interoperability. &lt;br /&gt;
&lt;br /&gt;
In Clojure's model, value calculation is purely functional. Values never change. New values are functions of old. But, logical identity is well supported via atomic references to values. The value of a reference (state of an identity) is always observable without coordination and freely shareable between threads.&lt;br /&gt;
When programs are constructed this way, functional value calculation is independent of identity-value association. This makes clojure easier to understand and test.&lt;br /&gt;
&lt;br /&gt;
====Example Using Functional Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
Consider the following functional programming example in Clojure-&lt;br /&gt;
 (defn make-adder [x]&lt;br /&gt;
   (let [y x]&lt;br /&gt;
     (fn [z] (+ y z))))&lt;br /&gt;
 (def add2 (make-adder 2))&lt;br /&gt;
 (add2 4)&lt;br /&gt;
&lt;br /&gt;
Here,'''''defn make-adder [x]''''' defines a function called ''make-adder''.'''''let [y x]''''' gives a local name y for the value x. Since the scope of any local names is lexical, a function created in the scope of local names will close over their values.'''''fn [z] (+ y z)''''' does the addition of y and z.&lt;br /&gt;
''&lt;br /&gt;
'''def add2 (make-adder 2)''''' calls the function ''make-adder'' passing the parameter 2 and calls this as ''add2''.Now, ''add2'' has computed 2+z. When '''''add2 4''''' is called it computes 2+4=6&lt;br /&gt;
&lt;br /&gt;
====Example Using Object-Oriented Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
The following program implements Run-Time Polymorphism which is an object-oriented programming concept.&lt;br /&gt;
 (defmulti encounter (fn [x y] [(:Species x) (:Species y)]))&lt;br /&gt;
 (defmethod encounter [:Bunny :Lion] [b l] :run-away)&lt;br /&gt;
 (defmethod encounter [:Lion :Bunny] [l b] :eat)&lt;br /&gt;
 (defmethod encounter [:Lion :Lion] [l1 l2] :fight)&lt;br /&gt;
 (defmethod encounter [:Bunny :Bunny] [b1 b2] :mate)&lt;br /&gt;
 (def b1 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def b2 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def l1 {:Species :Lion :other :stuff})&lt;br /&gt;
 (def l2 {:Species :Lion :other :stuff})&lt;br /&gt;
 &lt;br /&gt;
 (encounter b1 l1)&lt;br /&gt;
 -&amp;gt; :run-away&lt;br /&gt;
 (encounter l1 l2)&lt;br /&gt;
 -&amp;gt; :fight&lt;br /&gt;
&lt;br /&gt;
Here,'''''defmulti''''' is used to define multiple methods which have the same method name '''''encounter'''''.Depending on the parameters passed to the encounter method, one of the four methods is called.&lt;br /&gt;
'''''def''''' defines each of the different species.&lt;br /&gt;
When, '''''(encounter b1 l1)''''' is called, the first ''encounter'' method is called with the parameters ''Bunny'' and ''Lion''. As a result, ''run-away'' is printed.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Functional_programming Wikipedia - Functional Programming]&lt;br /&gt;
#[http://www.cs.cornell.edu/riccardo/prog-smlnj/notes-011001.pdf Notes on programming Standard ML of New Jersey]&lt;br /&gt;
#[http://users.dickinson.edu/~braught/courses/cs132f01/classes/code/Factorial.src.html Introduction to Computing - Dickinson College]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Object-oriented_programming Wikipedia - Object Oriented Programming]&lt;br /&gt;
#[http://searchsoa.techtarget.com/sDefinition/0,,sid26_gci212681,00.html  More on Object Oriented Programming]&lt;br /&gt;
#[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas Understanding Ruby Blocks, Procs and Lambdas - Robert Sosinski]&lt;br /&gt;
#[http://www.codingday.com/power-of-functional-programming-its-features-and-its-future/ Power of Functional Programming, its Features and its Future]&lt;br /&gt;
#[http://skillsmatter.com/podcast/open-source-dot-net/mike-wagg-mark-needham-functional-and-oo-approaches-to-c-sharp-programming Mixing Functional and Object Oriented Approaches to Programming in C#]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Programming_paradigm Programming Paradigm]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Recursion Recursion]&lt;br /&gt;
#[http://www.scala-lang.org/ Scala]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Scala_%28programming_language%29 Scala Wikipedia]&lt;br /&gt;
#[http://clojure.org/ Clojure]&lt;br /&gt;
#[http://www.ruby-lang.org/en/ Ruby]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Standard_ML Standard ML]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Haskell_%28programming_language%29 Haskell]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/ML_%28programming_language%29 ML Family]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/C%2B%2B C++ Programming Language]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Visual_Basic_.NET Visual Basic .Net]&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63478</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63478"/>
		<updated>2012-09-11T01:33:22Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Mixing Functional and Object-Oriented Code in Scala */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and data is immutable****. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily. &lt;br /&gt;
&lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-oriented Programming =&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm organized around interacting &amp;quot;objects&amp;quot;(usually instances of a class) rather than &amp;quot;actions&amp;quot; and data rather than logic. A basic principle of OOP is that a program consists of a list of subroutines which can perform individually. &lt;br /&gt;
&lt;br /&gt;
An object-oriented programming language provides support for the following object-oriented concepts--object, class, interface and inheritance. To illustrate this idea clearly and vividly let's review the following example-- your limbs. The &amp;quot;Limbs&amp;quot; is a class. Your body has two objects of type &amp;quot;limbs&amp;quot;, named arms and legs. Their main functions are controlled/ managed by a set of biological signals sent from central nervous system( through an interface). So the nervous system is an interface which your body uses to interact with your limbs. The &amp;quot;limbs&amp;quot; is a well architected class. The &amp;quot;legs&amp;quot; has a subclass which contains &amp;quot;left leg&amp;quot; and &amp;quot;Right leg&amp;quot;. The &amp;quot;legs&amp;quot; is being re-used to create the left leg and right leg by slightly changing the properties of it. If the &amp;quot;legs&amp;quot; owns attributes like length, color of skin etc, then the subclass, which contains &amp;quot;left leg&amp;quot; and &amp;quot;right leg&amp;quot; in this case, automatically inherit these attributes( that is called inheritance).&lt;br /&gt;
&lt;br /&gt;
We could code in object-oriented paradigm as:&lt;br /&gt;
&lt;br /&gt;
  class Limbs  /*define a class of limbs*/&lt;br /&gt;
    def initialize(limbs,length,colorofskin)&lt;br /&gt;
    @limbs=limbs&lt;br /&gt;
    @length=length&lt;br /&gt;
    @colorofskin=colorofskin&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  limbs=Limbs.new(&amp;quot;legs&amp;quot;,&amp;quot;100cm&amp;quot;,&amp;quot;white&amp;quot;)  /*create a new object in class &amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
  class Legs&amp;lt;Limbs   /*create a subclass &amp;quot;Legs&amp;quot;,which belong to class&amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
    def initialize(legs,length,colorofskin)&lt;br /&gt;
      super(length,colorofskin)&lt;br /&gt;
      @legs=legs&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
  legs=legs.new(&amp;quot;left leg&amp;quot;) /*create a new object in class of &amp;quot;Legs&amp;quot;*/&lt;br /&gt;
&lt;br /&gt;
== Features of Object-oriented Programming ==&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]. A programmer can simply create a new object that inherits many of its features from super-class. And also, they can overwrite existing operations or add new ones.This makes object-oriented programs easier to modify.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation].This refers to hiding the internal representation of the object from the outside view. You can hide unnecessary implementation details from the object user. One of the benefits of encapsulation is data protection.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism].This allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Consider the operator '+', for numbers it will generate the sum, but for strings it will produce a third string which concatenates the input strings.&lt;br /&gt;
&lt;br /&gt;
== Advantages of Object-oriented Programming ==&lt;br /&gt;
* Simplicity: we use software objects to simulate real world objects, so the complexity is reduced and the program structure is very clear.&lt;br /&gt;
* Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.&lt;br /&gt;
* Modifiability: programmers can easily make minor changes in the data representation or operations in an OOP. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.&lt;br /&gt;
* Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.&lt;br /&gt;
* Maintainability: objects can be maintained separately, making locating and fixing problems easier.&lt;br /&gt;
* Re-usability: objects can be reused in different programs.&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
In object-oriented world, data and operations are grouped together into modular units called objects and we combine objects into structured networks to form a program. The results are depend on arguments and objects' state at method invocation time. While in functional world, the basic elements are variables in the mathematical sense and functions in the mathematical sense. Functional programming can reduce side-effects. If there is no side-effects, it means your can apply the function at anywhere freely. No matter how you apply this function, the same input arguments produce the same results.&lt;br /&gt;
&lt;br /&gt;
According to above-mentioned information, we can perform functional programming on an object-oriented programming language because:&lt;br /&gt;
1). object can have constant state &lt;br /&gt;
2). method can depend only on its arguments and context available at method definition time&lt;br /&gt;
&lt;br /&gt;
Combining both these paradigms not only provide us a robust design structure, but also enable the programmers to develop solutions to complex problems quickly and effectively. One of the cornerstone of mixing functional and object-oriented code is treating functions as objects.It means that we can pass functions as arguments, store it and return them from other functions. This is highly useful in an user interface code where it can be used as call back functions which gets called when an event occurs(event driven programming).&lt;br /&gt;
&lt;br /&gt;
Some of the basic features of Functional Programming which can be combined with Object Oriented paradigm are:&lt;br /&gt;
&lt;br /&gt;
* Lambda Calculus&lt;br /&gt;
* Currying&lt;br /&gt;
* Powerful pattern matching&lt;br /&gt;
&lt;br /&gt;
Let us now understand how each of the above feature of Functional language fits in the Object Oriented paradigm.&lt;br /&gt;
&lt;br /&gt;
=== Lambda Calculus ===&lt;br /&gt;
Lambda calculus is the most critical basis of functional programming. A lambda expression is an anonymous expression that contain expressions and statements.Each expression stands for a function with one parameter. &lt;br /&gt;
&lt;br /&gt;
Let consider the following function:&lt;br /&gt;
&lt;br /&gt;
  def f(x)&lt;br /&gt;
  return x**2 &lt;br /&gt;
  print f(4)&lt;br /&gt;
&lt;br /&gt;
We can use a lambda calculus to compute this expression without assigning it to a variable: &lt;br /&gt;
&lt;br /&gt;
  (lambda x:x**x)(4)  &lt;br /&gt;
&lt;br /&gt;
We can see that these two code snippets have the same results. It is more concise and flexible to define with lambda.&lt;br /&gt;
The above is a pure functional approach. In order to make code more state-less and concise, lambdas can be embedded inside the object-oriented language. The below code in Python demonstrates the use of lambda in a closure:&lt;br /&gt;
&lt;br /&gt;
  def fun(x):&lt;br /&gt;
    return x%3==0&lt;br /&gt;
    str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
    filter(fun,str)&lt;br /&gt;
&lt;br /&gt;
The above code works to find numbers which are divisible by 3.&lt;br /&gt;
We can simplify the code by the use of lambda as following:&lt;br /&gt;
&lt;br /&gt;
  str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
  print filter(lambda x: x%3==0, str)&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
A number of programming languages support mixing of both functional and object-oriented code. Three of these (Scala, Ruby, and Conjure), are described in more detail below.&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky. It supports mixing functional and object-oriented code.&lt;br /&gt;
&lt;br /&gt;
==== Mixing Functional and Object-Oriented Code in Scala ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object-oriented and functional programming. How can this happen? The functional world advocates immutability, but the object-oriented world focuses on the state and how to change it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . A rough translation into Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as:&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks much simpler and less verbose. Even though the above example shows an immutable collection, scala also provides mutable collections and object types in the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So it's the best of both worlds. Another part of the functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
==== Implicits in Scala ====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. This feature is often called as [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching] because you are splitting open the class and adding/overriding methods (in)|(to) the class. Because other libraries may depend on some methods which you changed, often this leads to unexpected behavior at runtime. However, Scala provides yet another feature called [http://en.wikipedia.org/wiki/Implicit_function implicits] which helps you do this better.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Ruby is another language that, like Scala, supports mixing functional and object-oriented code. It is a dynamically typed Object-Oriented Language which supports multiple programming paradigms, including functional, object-oriented, imperative and reflective. In Ruby, everything is an object, every bit of information and code can have its own properties and actions. However, Ruby’s blocks can be functional. A Ruby programmer can attach a closure to any method, which generates a functional block inside an object oriented code. A closure is a piece of code that can access the lexical environment of its definition [http://www.ruby-lang.org/en/ 11].&lt;br /&gt;
&lt;br /&gt;
==== Ruby Mixing Example ====&lt;br /&gt;
&lt;br /&gt;
Consider the following code snippet in Ruby which uses Object Oriented concepts like Classes and functional programming concepts like lambda.&lt;br /&gt;
&lt;br /&gt;
 class Multiply&lt;br /&gt;
   def initialize(n)&lt;br /&gt;
     @block = lambda {|a| n * a}&lt;br /&gt;
   end&lt;br /&gt;
   def mul(a)&lt;br /&gt;
     @block.call a&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 twoMultiplier = Multiply.new 2                     &lt;br /&gt;
 puts twoMultiplier.mul(6)&lt;br /&gt;
&lt;br /&gt;
Here,'''''@block''''' is a closure. When we call the class ''Multiply'' using '''''twoAdder = Multiply.new 2''''' ,the ''initialize'' method is called by passing the parameter 2. Here n=2 binds itself to the block. So @block will be 2*a, that is,the closure remembers the parameter with which the initialize method was called even after the initialize method exits.  &lt;br /&gt;
&lt;br /&gt;
This value is used when the block is called in the add method.  &lt;br /&gt;
Thus,'''''twoMultiplier.mul(6)''''' will return 2*6 = 12&lt;br /&gt;
&lt;br /&gt;
==== Functional Style Coding in Ruby Blocks ====&lt;br /&gt;
&lt;br /&gt;
Blocks are basically nameless functions which can be passed to a function and then that function can invoke the passed in nameless function. This is a common style called [http://en.wikipedia.org/wiki/Higher-order_function higher order functions] among languages that handle functions as first class objects. Basically blocks can be designed for loop abstraction and lets the user to design their own way of iterating the values, thereby hiding the implementation details. &lt;br /&gt;
For example, if we want to iterate backwards from the end to the beginning without revealing its internal implementations, we could implement the loop logic inside the block and pass it to a method or function.&lt;br /&gt;
&lt;br /&gt;
Here is a [http://www.ruby-lang.org/en/ Ruby] implementation of block:&lt;br /&gt;
 &lt;br /&gt;
 def printlist(array,&amp;amp;reverse)&lt;br /&gt;
    array.each do |element|&lt;br /&gt;
       puts &amp;quot;array element: #{element}&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
    reverse.call(array)   /* Here it prints the reverse implementation of list*/&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
 printlist([1,2,3,4,5,6]) { |array| &lt;br /&gt;
   array.reverse.each do |element| &lt;br /&gt;
     puts &amp;quot;array element: #{element}&amp;quot; &lt;br /&gt;
   end &lt;br /&gt;
 }&lt;br /&gt;
The statements between { } is a block and it gets called by &amp;lt;code&amp;gt;reverse.call(array)&amp;lt;/code&amp;gt;within the printlist method.&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language, and it is a dialect of Lisp. It is not a pure functional language. Instead, it is a dynamically typed language. Just like Java it runs on JVM platform, but its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
(functions arguments...)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The function and its arguments are enclosed in paranthesis. It has features like immutable data structures, high-order functions, recursion, and easy and fast java interoperability. &lt;br /&gt;
&lt;br /&gt;
In Clojure's model, value calculation is purely functional. Values never change. New values are functions of old. But, logical identity is well supported via atomic references to values. The value of a reference (state of an identity) is always observable without coordination and freely shareable between threads.&lt;br /&gt;
When programs are constructed this way, functional value calculation is independent of identity-value association. This makes clojure easier to understand and test.&lt;br /&gt;
&lt;br /&gt;
====Example Using Functional Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
Consider the following functional programming example in Clojure-&lt;br /&gt;
 (defn make-adder [x]&lt;br /&gt;
   (let [y x]&lt;br /&gt;
     (fn [z] (+ y z))))&lt;br /&gt;
 (def add2 (make-adder 2))&lt;br /&gt;
 (add2 4)&lt;br /&gt;
&lt;br /&gt;
Here,'''''defn make-adder [x]''''' defines a function called ''make-adder''.'''''let [y x]''''' gives a local name y for the value x. Since the scope of any local names is lexical, a function created in the scope of local names will close over their values.'''''fn [z] (+ y z)''''' does the addition of y and z.&lt;br /&gt;
''&lt;br /&gt;
'''def add2 (make-adder 2)''''' calls the function ''make-adder'' passing the parameter 2 and calls this as ''add2''.Now, ''add2'' has computed 2+z. When '''''add2 4''''' is called it computes 2+4=6&lt;br /&gt;
&lt;br /&gt;
====Example Using Object-Oriented Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
The following program implements Run-Time Polymorphism which is an object-oriented programming concept.&lt;br /&gt;
 (defmulti encounter (fn [x y] [(:Species x) (:Species y)]))&lt;br /&gt;
 (defmethod encounter [:Bunny :Lion] [b l] :run-away)&lt;br /&gt;
 (defmethod encounter [:Lion :Bunny] [l b] :eat)&lt;br /&gt;
 (defmethod encounter [:Lion :Lion] [l1 l2] :fight)&lt;br /&gt;
 (defmethod encounter [:Bunny :Bunny] [b1 b2] :mate)&lt;br /&gt;
 (def b1 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def b2 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def l1 {:Species :Lion :other :stuff})&lt;br /&gt;
 (def l2 {:Species :Lion :other :stuff})&lt;br /&gt;
 &lt;br /&gt;
 (encounter b1 l1)&lt;br /&gt;
 -&amp;gt; :run-away&lt;br /&gt;
 (encounter l1 l2)&lt;br /&gt;
 -&amp;gt; :fight&lt;br /&gt;
&lt;br /&gt;
Here,'''''defmulti''''' is used to define multiple methods which have the same method name '''''encounter'''''.Depending on the parameters passed to the encounter method, one of the four methods is called.&lt;br /&gt;
'''''def''''' defines each of the different species.&lt;br /&gt;
When, '''''(encounter b1 l1)''''' is called, the first ''encounter'' method is called with the parameters ''Bunny'' and ''Lion''. As a result, ''run-away'' is printed.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63477</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63477"/>
		<updated>2012-09-11T01:26:52Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: Deleted unrelevant sections about Scala&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and data is immutable****. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily. &lt;br /&gt;
&lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-oriented Programming =&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm organized around interacting &amp;quot;objects&amp;quot;(usually instances of a class) rather than &amp;quot;actions&amp;quot; and data rather than logic. A basic principle of OOP is that a program consists of a list of subroutines which can perform individually. &lt;br /&gt;
&lt;br /&gt;
An object-oriented programming language provides support for the following object-oriented concepts--object, class, interface and inheritance. To illustrate this idea clearly and vividly let's review the following example-- your limbs. The &amp;quot;Limbs&amp;quot; is a class. Your body has two objects of type &amp;quot;limbs&amp;quot;, named arms and legs. Their main functions are controlled/ managed by a set of biological signals sent from central nervous system( through an interface). So the nervous system is an interface which your body uses to interact with your limbs. The &amp;quot;limbs&amp;quot; is a well architected class. The &amp;quot;legs&amp;quot; has a subclass which contains &amp;quot;left leg&amp;quot; and &amp;quot;Right leg&amp;quot;. The &amp;quot;legs&amp;quot; is being re-used to create the left leg and right leg by slightly changing the properties of it. If the &amp;quot;legs&amp;quot; owns attributes like length, color of skin etc, then the subclass, which contains &amp;quot;left leg&amp;quot; and &amp;quot;right leg&amp;quot; in this case, automatically inherit these attributes( that is called inheritance).&lt;br /&gt;
&lt;br /&gt;
We could code in object-oriented paradigm as:&lt;br /&gt;
&lt;br /&gt;
  class Limbs  /*define a class of limbs*/&lt;br /&gt;
    def initialize(limbs,length,colorofskin)&lt;br /&gt;
    @limbs=limbs&lt;br /&gt;
    @length=length&lt;br /&gt;
    @colorofskin=colorofskin&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  limbs=Limbs.new(&amp;quot;legs&amp;quot;,&amp;quot;100cm&amp;quot;,&amp;quot;white&amp;quot;)  /*create a new object in class &amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
  class Legs&amp;lt;Limbs   /*create a subclass &amp;quot;Legs&amp;quot;,which belong to class&amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
    def initialize(legs,length,colorofskin)&lt;br /&gt;
      super(length,colorofskin)&lt;br /&gt;
      @legs=legs&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
  legs=legs.new(&amp;quot;left leg&amp;quot;) /*create a new object in class of &amp;quot;Legs&amp;quot;*/&lt;br /&gt;
&lt;br /&gt;
== Features of Object-oriented Programming ==&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]. A programmer can simply create a new object that inherits many of its features from super-class. And also, they can overwrite existing operations or add new ones.This makes object-oriented programs easier to modify.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation].This refers to hiding the internal representation of the object from the outside view. You can hide unnecessary implementation details from the object user. One of the benefits of encapsulation is data protection.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism].This allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Consider the operator '+', for numbers it will generate the sum, but for strings it will produce a third string which concatenates the input strings.&lt;br /&gt;
&lt;br /&gt;
== Advantages of Object-oriented Programming ==&lt;br /&gt;
* Simplicity: we use software objects to simulate real world objects, so the complexity is reduced and the program structure is very clear.&lt;br /&gt;
* Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.&lt;br /&gt;
* Modifiability: programmers can easily make minor changes in the data representation or operations in an OOP. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.&lt;br /&gt;
* Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.&lt;br /&gt;
* Maintainability: objects can be maintained separately, making locating and fixing problems easier.&lt;br /&gt;
* Re-usability: objects can be reused in different programs.&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
In object-oriented world, data and operations are grouped together into modular units called objects and we combine objects into structured networks to form a program. The results are depend on arguments and objects' state at method invocation time. While in functional world, the basic elements are variables in the mathematical sense and functions in the mathematical sense. Functional programming can reduce side-effects. If there is no side-effects, it means your can apply the function at anywhere freely. No matter how you apply this function, the same input arguments produce the same results.&lt;br /&gt;
&lt;br /&gt;
According to above-mentioned information, we can perform functional programming on an object-oriented programming language because:&lt;br /&gt;
1). object can have constant state &lt;br /&gt;
2). method can depend only on its arguments and context available at method definition time&lt;br /&gt;
&lt;br /&gt;
Combining both these paradigms not only provide us a robust design structure, but also enable the programmers to develop solutions to complex problems quickly and effectively. One of the cornerstone of mixing functional and object-oriented code is treating functions as objects.It means that we can pass functions as arguments, store it and return them from other functions. This is highly useful in an user interface code where it can be used as call back functions which gets called when an event occurs(event driven programming).&lt;br /&gt;
&lt;br /&gt;
Some of the basic features of Functional Programming which can be combined with Object Oriented paradigm are:&lt;br /&gt;
&lt;br /&gt;
* Lambda Calculus&lt;br /&gt;
* Currying&lt;br /&gt;
* Powerful pattern matching&lt;br /&gt;
&lt;br /&gt;
Let us now understand how each of the above feature of Functional language fits in the Object Oriented paradigm.&lt;br /&gt;
&lt;br /&gt;
=== Lambda Calculus ===&lt;br /&gt;
Lambda calculus is the most critical basis of functional programming. A lambda expression is an anonymous expression that contain expressions and statements.Each expression stands for a function with one parameter. &lt;br /&gt;
&lt;br /&gt;
Let consider the following function:&lt;br /&gt;
&lt;br /&gt;
  def f(x)&lt;br /&gt;
  return x**2 &lt;br /&gt;
  print f(4)&lt;br /&gt;
&lt;br /&gt;
We can use a lambda calculus to compute this expression without assigning it to a variable: &lt;br /&gt;
&lt;br /&gt;
  (lambda x:x**x)(4)  &lt;br /&gt;
&lt;br /&gt;
We can see that these two code snippets have the same results. It is more concise and flexible to define with lambda.&lt;br /&gt;
The above is a pure functional approach. In order to make code more state-less and concise, lambdas can be embedded inside the object-oriented language. The below code in Python demonstrates the use of lambda in a closure:&lt;br /&gt;
&lt;br /&gt;
  def fun(x):&lt;br /&gt;
    return x%3==0&lt;br /&gt;
    str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
    filter(fun,str)&lt;br /&gt;
&lt;br /&gt;
The above code works to find numbers which are divisible by 3.&lt;br /&gt;
We can simplify the code by the use of lambda as following:&lt;br /&gt;
&lt;br /&gt;
  str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
  print filter(lambda x: x%3==0, str)&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
A number of programming languages support mixing of both functional and object-oriented code. Three of these (Scala, Ruby, and Conjure), are described in more detail below.&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky. It supports mixing functional and object-oriented code.&lt;br /&gt;
&lt;br /&gt;
==== Mixing Functional and Object-Oriented Code in Scala ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object-oriented and functional programming. How can this happen? Functional world advocates immutability but object oriented world is all about state and how do you mutate it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . Roughly translating the above line to Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as below&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks so much simpler and less verbose. Even though the above example shows immutable collection example, scala also provides mutable collection and object types under the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As it can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So its the best of both worlds. Another part of functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
==== Implicits in Scala ====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. This feature is often called as [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching] because you are splitting open the class and adding/overriding methods (in)|(to) the class. Because other libraries may depend on some methods which you changed, often this leads to unexpected behavior at runtime. However, Scala provides yet another feature called [http://en.wikipedia.org/wiki/Implicit_function implicits] which helps you do this better.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Ruby is another language that, like Scala, supports mixing functional and object-oriented code. It is a dynamically typed Object-Oriented Language which supports multiple programming paradigms, including functional, object-oriented, imperative and reflective. In Ruby, everything is an object, every bit of information and code can have its own properties and actions. However, Ruby’s blocks can be functional. A Ruby programmer can attach a closure to any method, which generates a functional block inside an object oriented code. A closure is a piece of code that can access the lexical environment of its definition [http://www.ruby-lang.org/en/ 11].&lt;br /&gt;
&lt;br /&gt;
==== Ruby Mixing Example ====&lt;br /&gt;
&lt;br /&gt;
Consider the following code snippet in Ruby which uses Object Oriented concepts like Classes and functional programming concepts like lambda.&lt;br /&gt;
&lt;br /&gt;
 class Multiply&lt;br /&gt;
   def initialize(n)&lt;br /&gt;
     @block = lambda {|a| n * a}&lt;br /&gt;
   end&lt;br /&gt;
   def mul(a)&lt;br /&gt;
     @block.call a&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 twoMultiplier = Multiply.new 2                     &lt;br /&gt;
 puts twoMultiplier.mul(6)&lt;br /&gt;
&lt;br /&gt;
Here,'''''@block''''' is a closure. When we call the class ''Multiply'' using '''''twoAdder = Multiply.new 2''''' ,the ''initialize'' method is called by passing the parameter 2. Here n=2 binds itself to the block. So @block will be 2*a, that is,the closure remembers the parameter with which the initialize method was called even after the initialize method exits.  &lt;br /&gt;
&lt;br /&gt;
This value is used when the block is called in the add method.  &lt;br /&gt;
Thus,'''''twoMultiplier.mul(6)''''' will return 2*6 = 12&lt;br /&gt;
&lt;br /&gt;
==== Functional Style Coding in Ruby Blocks ====&lt;br /&gt;
&lt;br /&gt;
Blocks are basically nameless functions which can be passed to a function and then that function can invoke the passed in nameless function. This is a common style called [http://en.wikipedia.org/wiki/Higher-order_function higher order functions] among languages that handle functions as first class objects. Basically blocks can be designed for loop abstraction and lets the user to design their own way of iterating the values, thereby hiding the implementation details. &lt;br /&gt;
For example, if we want to iterate backwards from the end to the beginning without revealing its internal implementations, we could implement the loop logic inside the block and pass it to a method or function.&lt;br /&gt;
&lt;br /&gt;
Here is a [http://www.ruby-lang.org/en/ Ruby] implementation of block:&lt;br /&gt;
 &lt;br /&gt;
 def printlist(array,&amp;amp;reverse)&lt;br /&gt;
    array.each do |element|&lt;br /&gt;
       puts &amp;quot;array element: #{element}&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
    reverse.call(array)   /* Here it prints the reverse implementation of list*/&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
 printlist([1,2,3,4,5,6]) { |array| &lt;br /&gt;
   array.reverse.each do |element| &lt;br /&gt;
     puts &amp;quot;array element: #{element}&amp;quot; &lt;br /&gt;
   end &lt;br /&gt;
 }&lt;br /&gt;
The statements between { } is a block and it gets called by &amp;lt;code&amp;gt;reverse.call(array)&amp;lt;/code&amp;gt;within the printlist method.&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language, and it is a dialect of Lisp. It is not a pure functional language. Instead, it is a dynamically typed language. Just like Java it runs on JVM platform, but its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
(functions arguments...)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The function and its arguments are enclosed in paranthesis. It has features like immutable data structures, high-order functions, recursion, and easy and fast java interoperability. &lt;br /&gt;
&lt;br /&gt;
In Clojure's model, value calculation is purely functional. Values never change. New values are functions of old. But, logical identity is well supported via atomic references to values. The value of a reference (state of an identity) is always observable without coordination and freely shareable between threads.&lt;br /&gt;
When programs are constructed this way, functional value calculation is independent of identity-value association. This makes clojure easier to understand and test.&lt;br /&gt;
&lt;br /&gt;
====Example Using Functional Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
Consider the following functional programming example in Clojure-&lt;br /&gt;
 (defn make-adder [x]&lt;br /&gt;
   (let [y x]&lt;br /&gt;
     (fn [z] (+ y z))))&lt;br /&gt;
 (def add2 (make-adder 2))&lt;br /&gt;
 (add2 4)&lt;br /&gt;
&lt;br /&gt;
Here,'''''defn make-adder [x]''''' defines a function called ''make-adder''.'''''let [y x]''''' gives a local name y for the value x. Since the scope of any local names is lexical, a function created in the scope of local names will close over their values.'''''fn [z] (+ y z)''''' does the addition of y and z.&lt;br /&gt;
''&lt;br /&gt;
'''def add2 (make-adder 2)''''' calls the function ''make-adder'' passing the parameter 2 and calls this as ''add2''.Now, ''add2'' has computed 2+z. When '''''add2 4''''' is called it computes 2+4=6&lt;br /&gt;
&lt;br /&gt;
====Example Using Object-Oriented Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
The following program implements Run-Time Polymorphism which is an object-oriented programming concept.&lt;br /&gt;
 (defmulti encounter (fn [x y] [(:Species x) (:Species y)]))&lt;br /&gt;
 (defmethod encounter [:Bunny :Lion] [b l] :run-away)&lt;br /&gt;
 (defmethod encounter [:Lion :Bunny] [l b] :eat)&lt;br /&gt;
 (defmethod encounter [:Lion :Lion] [l1 l2] :fight)&lt;br /&gt;
 (defmethod encounter [:Bunny :Bunny] [b1 b2] :mate)&lt;br /&gt;
 (def b1 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def b2 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def l1 {:Species :Lion :other :stuff})&lt;br /&gt;
 (def l2 {:Species :Lion :other :stuff})&lt;br /&gt;
 &lt;br /&gt;
 (encounter b1 l1)&lt;br /&gt;
 -&amp;gt; :run-away&lt;br /&gt;
 (encounter l1 l2)&lt;br /&gt;
 -&amp;gt; :fight&lt;br /&gt;
&lt;br /&gt;
Here,'''''defmulti''''' is used to define multiple methods which have the same method name '''''encounter'''''.Depending on the parameters passed to the encounter method, one of the four methods is called.&lt;br /&gt;
'''''def''''' defines each of the different species.&lt;br /&gt;
When, '''''(encounter b1 l1)''''' is called, the first ''encounter'' method is called with the parameters ''Bunny'' and ''Lion''. As a result, ''run-away'' is printed.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63471</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63471"/>
		<updated>2012-09-11T01:18:02Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: Added Clojure Section and corrected grammar.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and data is immutable****. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily. &lt;br /&gt;
&lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-oriented Programming =&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm organized around interacting &amp;quot;objects&amp;quot;(usually instances of a class) rather than &amp;quot;actions&amp;quot; and data rather than logic. A basic principle of OOP is that a program consists of a list of subroutines which can perform individually. &lt;br /&gt;
&lt;br /&gt;
An object-oriented programming language provides support for the following object-oriented concepts--object, class, interface and inheritance. To illustrate this idea clearly and vividly let's review the following example-- your limbs. The &amp;quot;Limbs&amp;quot; is a class. Your body has two objects of type &amp;quot;limbs&amp;quot;, named arms and legs. Their main functions are controlled/ managed by a set of biological signals sent from central nervous system( through an interface). So the nervous system is an interface which your body uses to interact with your limbs. The &amp;quot;limbs&amp;quot; is a well architected class. The &amp;quot;legs&amp;quot; has a subclass which contains &amp;quot;left leg&amp;quot; and &amp;quot;Right leg&amp;quot;. The &amp;quot;legs&amp;quot; is being re-used to create the left leg and right leg by slightly changing the properties of it. If the &amp;quot;legs&amp;quot; owns attributes like length, color of skin etc, then the subclass, which contains &amp;quot;left leg&amp;quot; and &amp;quot;right leg&amp;quot; in this case, automatically inherit these attributes( that is called inheritance).&lt;br /&gt;
&lt;br /&gt;
We could code in object-oriented paradigm as:&lt;br /&gt;
&lt;br /&gt;
  class Limbs  /*define a class of limbs*/&lt;br /&gt;
    def initialize(limbs,length,colorofskin)&lt;br /&gt;
    @limbs=limbs&lt;br /&gt;
    @length=length&lt;br /&gt;
    @colorofskin=colorofskin&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  limbs=Limbs.new(&amp;quot;legs&amp;quot;,&amp;quot;100cm&amp;quot;,&amp;quot;white&amp;quot;)  /*create a new object in class &amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
  class Legs&amp;lt;Limbs   /*create a subclass &amp;quot;Legs&amp;quot;,which belong to class&amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
    def initialize(legs,length,colorofskin)&lt;br /&gt;
      super(length,colorofskin)&lt;br /&gt;
      @legs=legs&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
  legs=legs.new(&amp;quot;left leg&amp;quot;) /*create a new object in class of &amp;quot;Legs&amp;quot;*/&lt;br /&gt;
&lt;br /&gt;
== Features of Object-oriented Programming ==&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]. A programmer can simply create a new object that inherits many of its features from super-class. And also, they can overwrite existing operations or add new ones.This makes object-oriented programs easier to modify.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation].This refers to hiding the internal representation of the object from the outside view. You can hide unnecessary implementation details from the object user. One of the benefits of encapsulation is data protection.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism].This allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Consider the operator '+', for numbers it will generate the sum, but for strings it will produce a third string which concatenates the input strings.&lt;br /&gt;
&lt;br /&gt;
== Advantages of Object-oriented Programming ==&lt;br /&gt;
* Simplicity: we use software objects to simulate real world objects, so the complexity is reduced and the program structure is very clear.&lt;br /&gt;
* Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.&lt;br /&gt;
* Modifiability: programmers can easily make minor changes in the data representation or operations in an OOP. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.&lt;br /&gt;
* Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.&lt;br /&gt;
* Maintainability: objects can be maintained separately, making locating and fixing problems easier.&lt;br /&gt;
* Re-usability: objects can be reused in different programs.&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
In object-oriented world, data and operations are grouped together into modular units called objects and we combine objects into structured networks to form a program. The results are depend on arguments and objects' state at method invocation time. While in functional world, the basic elements are variables in the mathematical sense and functions in the mathematical sense. Functional programming can reduce side-effects. If there is no side-effects, it means your can apply the function at anywhere freely. No matter how you apply this function, the same input arguments produce the same results.&lt;br /&gt;
&lt;br /&gt;
According to above-mentioned information, we can perform functional programming on an object-oriented programming language because:&lt;br /&gt;
1). object can have constant state &lt;br /&gt;
2). method can depend only on its arguments and context available at method definition time&lt;br /&gt;
&lt;br /&gt;
Combining both these paradigms not only provide us a robust design structure, but also enable the programmers to develop solutions to complex problems quickly and effectively. One of the cornerstone of mixing functional and object-oriented code is treating functions as objects.It means that we can pass functions as arguments, store it and return them from other functions. This is highly useful in an user interface code where it can be used as call back functions which gets called when an event occurs(event driven programming).&lt;br /&gt;
&lt;br /&gt;
Some of the basic features of Functional Programming which can be combined with Object Oriented paradigm are:&lt;br /&gt;
&lt;br /&gt;
* Lambda Calculus&lt;br /&gt;
* Currying&lt;br /&gt;
* Powerful pattern matching&lt;br /&gt;
&lt;br /&gt;
Let us now understand how each of the above feature of Functional language fits in the Object Oriented paradigm.&lt;br /&gt;
&lt;br /&gt;
=== Lambda Calculus ===&lt;br /&gt;
Lambda calculus is the most critical basis of functional programming. A lambda expression is an anonymous expression that contain expressions and statements.Each expression stands for a function with one parameter. &lt;br /&gt;
&lt;br /&gt;
Let consider the following function:&lt;br /&gt;
&lt;br /&gt;
  def f(x)&lt;br /&gt;
  return x**2 &lt;br /&gt;
  print f(4)&lt;br /&gt;
&lt;br /&gt;
We can use a lambda calculus to compute this expression without assigning it to a variable: &lt;br /&gt;
&lt;br /&gt;
  (lambda x:x**x)(4)  &lt;br /&gt;
&lt;br /&gt;
We can see that these two code snippets have the same results. It is more concise and flexible to define with lambda.&lt;br /&gt;
The above is a pure functional approach. In order to make code more state-less and concise, lambdas can be embedded inside the object-oriented language. The below code in Python demonstrates the use of lambda in a closure:&lt;br /&gt;
&lt;br /&gt;
  def fun(x):&lt;br /&gt;
    return x%3==0&lt;br /&gt;
    str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
    filter(fun,str)&lt;br /&gt;
&lt;br /&gt;
The above code works to find numbers which are divisible by 3.&lt;br /&gt;
We can simplify the code by the use of lambda as following:&lt;br /&gt;
&lt;br /&gt;
  str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
  print filter(lambda x: x%3==0, str)&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
A number of programming languages support mixing of both functional and object-oriented code. Three of these (Scala, Ruby, and Conjure), are described in more detail below.&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky. It has a number of features.&lt;br /&gt;
&lt;br /&gt;
==== Statically Typed ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] belongs to the family of languages which encode the type information of each and every variable in the generated code. The compiler makes sure you are not doing something incorrectly. For example, lets consider the following example of code where the type is not encoded,&lt;br /&gt;
&lt;br /&gt;
In [http://www.ruby-lang.org/en/ Ruby],&lt;br /&gt;
   irb(main):001:0&amp;gt; str=&amp;quot;Hello World&amp;quot;&lt;br /&gt;
    =&amp;gt; &amp;quot;Hello World&amp;quot;&lt;br /&gt;
    irb(main):002:0&amp;gt; puts str.class&lt;br /&gt;
    String&lt;br /&gt;
    irb(main):003:0&amp;gt; str=123&lt;br /&gt;
    =&amp;gt; 123&lt;br /&gt;
    irb(main):004:0&amp;gt; puts str.class&lt;br /&gt;
    Fixnum&lt;br /&gt;
&lt;br /&gt;
In the above example, first we define 'str' variable to be of type String and then as a number. So basically, no type information is associated with the variable at any point in the program. Hence we can easily reassociate that variable with an object/instance&lt;br /&gt;
of a different type. This is a feature of all dynamically typed languages(like Ruby, Python, Clojure). However most of the statically typed languages such as Scala, Java, C/C++ do not allow you do so. In [http://www.scala-lang.org/ Scala],&lt;br /&gt;
&lt;br /&gt;
  scala&amp;gt; var str=&amp;quot;Hello World&amp;quot;&lt;br /&gt;
  str: java.lang.String = Hello World&lt;br /&gt;
  scala&amp;gt; str=123&lt;br /&gt;
  &amp;lt;console&amp;gt;:6: error: type mismatch;&lt;br /&gt;
   found   : Int(123)&lt;br /&gt;
   required: java.lang.String&lt;br /&gt;
         str=123&lt;br /&gt;
&lt;br /&gt;
==== Mixed paradigm ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object oriented and functional programming. How can this happen? Functional world advocates immutability but object oriented world is all about state and how do you mutate it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . Roughly translating the above line to Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as below&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks so much simpler and less verbose. Even though the above example shows immutable collection example, scala also provides mutable collection and object types under the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As it can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So its the best of both worlds. Another part of functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
==== Sophisticated Syntax/Features ====&lt;br /&gt;
Sophisticated syntax and features are present in other functional languages like Haskell, (O)Caml and Erlang. Consider the following example,&lt;br /&gt;
&lt;br /&gt;
   val name = &amp;quot;Jackie Chan&amp;quot;&lt;br /&gt;
   println(name.getClass) //prints out String.&lt;br /&gt;
&lt;br /&gt;
Previously we saw that [http://www.scala-lang.org/ Scala] is a statically typed language and yet in the above example we don't specify what type &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; is. In Java, you would type in the following:&lt;br /&gt;
&lt;br /&gt;
 String name = &amp;quot;Jackie Chan&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In Java you specify what type the name variable is, but the [http://www.scala-lang.org/ scala] compiler can automatically detect the type of the variable even if you don't specify it. Consider the following example,&lt;br /&gt;
&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
 val persons = List(&lt;br /&gt;
                        Person(&amp;quot;Jackie Chan&amp;quot;, 51), Person(&amp;quot;Jet Li&amp;quot;, 41),&lt;br /&gt;
                        Person(&amp;quot;RajniKanth&amp;quot;, 51), Person(&amp;quot;Kamal Hasan&amp;quot;, 44),&lt;br /&gt;
                        Person(&amp;quot;Martin Odersky&amp;quot;, 18), Person(&amp;quot;Steve Yegge&amp;quot;, 23))&lt;br /&gt;
 //notice that you don't have to use 'new' keyword to create new instances. This is taken care of by the companion objects.&lt;br /&gt;
&lt;br /&gt;
The above lines of code create a list with 6 different persons(An immutable list)&lt;br /&gt;
&lt;br /&gt;
Now, just like ruby, scala supports the concepts of [http://en.wikipedia.org/wiki/Closure_(computer_science) closure]. Let's see what it is.&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( { p: Person =&amp;gt; p.age == 3})&lt;br /&gt;
&lt;br /&gt;
In the above set of lines, the code within the '{ }' brackets is a function's body. The compiler created a function which takes a single argument and returns either true or false. &lt;br /&gt;
&lt;br /&gt;
==== A Scalable Language ====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. This feature is often called as [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching] because you are splitting open the class and adding/overriding methods (in)|(to) the class. Because other libraries may depend on some methods which you changed, often this leads to unexpected behavior at runtime. However, Scala provides yet another feature called implicits which helps you do this better.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Ruby is another language that, like Scala, supports mixing functional and object-oriented code. It is a dynamically typed Object-Oriented Language which supports multiple programming paradigms, including functional, object-oriented, imperative and reflective. In Ruby, everything is an object, every bit of information and code can have its own properties and actions. However, Ruby’s blocks can be functional. A Ruby programmer can attach a closure to any method, which generates a functional block inside an object oriented code. A closure is a piece of code that can access the lexical environment of its definition [http://www.ruby-lang.org/en/ 11].&lt;br /&gt;
&lt;br /&gt;
==== Ruby Mixing Example ====&lt;br /&gt;
&lt;br /&gt;
Consider the following code snippet in Ruby which uses Object Oriented concepts like Classes and functional programming concepts like lambda.&lt;br /&gt;
&lt;br /&gt;
 class Multiply&lt;br /&gt;
   def initialize(n)&lt;br /&gt;
     @block = lambda {|a| n * a}&lt;br /&gt;
   end&lt;br /&gt;
   def mul(a)&lt;br /&gt;
     @block.call a&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 twoMultiplier = Multiply.new 2                     &lt;br /&gt;
 puts twoMultiplier.mul(6)&lt;br /&gt;
&lt;br /&gt;
Here,'''''@block''''' is a closure. When we call the class ''Multiply'' using '''''twoAdder = Multiply.new 2''''' ,the ''initialize'' method is called by passing the parameter 2. Here n=2 binds itself to the block. So @block will be 2*a, that is,the closure remembers the parameter with which the initialize method was called even after the initialize method exits.  &lt;br /&gt;
&lt;br /&gt;
This value is used when the block is called in the add method.  &lt;br /&gt;
Thus,'''''twoMultiplier.mul(6)''''' will return 2*6 = 12&lt;br /&gt;
&lt;br /&gt;
==== Functional Style Coding in Ruby Blocks ====&lt;br /&gt;
&lt;br /&gt;
Blocks are basically nameless functions which can be passed to a function and then that function can invoke the passed in nameless function. This is a common style called [http://en.wikipedia.org/wiki/Higher-order_function higher order functions] among languages that handle functions as first class objects. Basically blocks can be designed for loop abstraction and lets the user to design their own way of iterating the values, thereby hiding the implementation details. &lt;br /&gt;
For example, if we want to iterate backwards from the end to the beginning without revealing its internal implementations, we could implement the loop logic inside the block and pass it to a method or function.&lt;br /&gt;
&lt;br /&gt;
Here is a [http://www.ruby-lang.org/en/ Ruby] implementation of block:&lt;br /&gt;
 &lt;br /&gt;
 def printlist(array,&amp;amp;reverse)&lt;br /&gt;
    array.each do |element|&lt;br /&gt;
       puts &amp;quot;array element: #{element}&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
    reverse.call(array)   /* Here it prints the reverse implementation of list*/&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
 printlist([1,2,3,4,5,6]) { |array| &lt;br /&gt;
   array.reverse.each do |element| &lt;br /&gt;
     puts &amp;quot;array element: #{element}&amp;quot; &lt;br /&gt;
   end &lt;br /&gt;
 }&lt;br /&gt;
The statements between { } is a block and it gets called by &amp;lt;code&amp;gt;reverse.call(array)&amp;lt;/code&amp;gt;within the printlist method.&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language, and it is a dialect of Lisp. It is not a pure functional language. Instead, it is a dynamically typed language. Just like Java it runs on JVM platform, but its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
(functions arguments...)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The function and its arguments are enclosed in paranthesis. It has features like immutable data structures, high-order functions, recursion, and easy and fast java interoperability. &lt;br /&gt;
&lt;br /&gt;
In Clojure's model, value calculation is purely functional. Values never change. New values are functions of old. But, logical identity is well supported via atomic references to values. The value of a reference (state of an identity) is always observable without coordination and freely shareable between threads.&lt;br /&gt;
When programs are constructed this way, functional value calculation is independent of identity-value association. This makes clojure easier to understand and test.&lt;br /&gt;
&lt;br /&gt;
====Example Using Function Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
Consider the following functional programming example in Clojure-&lt;br /&gt;
 (defn make-adder [x]&lt;br /&gt;
   (let [y x]&lt;br /&gt;
     (fn [z] (+ y z))))&lt;br /&gt;
 (def add2 (make-adder 2))&lt;br /&gt;
 (add2 4)&lt;br /&gt;
&lt;br /&gt;
Here,'''''defn make-adder [x]''''' defines a function called ''make-adder''.'''''let [y x]''''' gives a local name y for the value x. Since the scope of any local names is lexical, a function created in the scope of local names will close over their values.'''''fn [z] (+ y z)''''' does the addition of y and z.&lt;br /&gt;
''&lt;br /&gt;
'''def add2 (make-adder 2)''''' calls the function ''make-adder'' passing the parameter 2 and calls this as ''add2''.Now, ''add2'' has computed 2+z. When '''''add2 4''''' is called it computes 2+4=6&lt;br /&gt;
&lt;br /&gt;
====Example Using Object-Oriented Technique in Clojure====&lt;br /&gt;
&lt;br /&gt;
The following program implements Run-Time Polymorphism which is an object-oriented programming concept.&lt;br /&gt;
 (defmulti encounter (fn [x y] [(:Species x) (:Species y)]))&lt;br /&gt;
 (defmethod encounter [:Bunny :Lion] [b l] :run-away)&lt;br /&gt;
 (defmethod encounter [:Lion :Bunny] [l b] :eat)&lt;br /&gt;
 (defmethod encounter [:Lion :Lion] [l1 l2] :fight)&lt;br /&gt;
 (defmethod encounter [:Bunny :Bunny] [b1 b2] :mate)&lt;br /&gt;
 (def b1 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def b2 {:Species :Bunny :other :stuff})&lt;br /&gt;
 (def l1 {:Species :Lion :other :stuff})&lt;br /&gt;
 (def l2 {:Species :Lion :other :stuff})&lt;br /&gt;
 &lt;br /&gt;
 (encounter b1 l1)&lt;br /&gt;
 -&amp;gt; :run-away&lt;br /&gt;
 (encounter l1 l2)&lt;br /&gt;
 -&amp;gt; :fight&lt;br /&gt;
&lt;br /&gt;
Here,'''''defmulti''''' is used to define multiple methods which have the same method name '''''encounter'''''.Depending on the parameters passed to the encounter method, one of the four methods is called.&lt;br /&gt;
'''''def''''' defines each of the different species.&lt;br /&gt;
When, '''''(encounter b1 l1)''''' is called, the first ''encounter'' method is called with the parameters ''Bunny'' and ''Lion''. As a result, ''run-away'' is printed.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63230</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63230"/>
		<updated>2012-09-09T22:41:11Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and data is immutable****. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily. &lt;br /&gt;
&lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-oriented Programming =&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm organized around interacting &amp;quot;objects&amp;quot;(usually instances of a class) rather than &amp;quot;actions&amp;quot; and data rather than logic. A basic principle of OOP is that a program consists of a list of subroutines which can perform individually. &lt;br /&gt;
&lt;br /&gt;
An object-oriented programming language provides support for the following object-oriented concepts--object, class, interface and inheritance. To illustrate this idea clearly and vividly let's review the following example-- your limbs. The &amp;quot;Limbs&amp;quot; is a class. Your body has two objects of type &amp;quot;limbs&amp;quot;, named arms and legs. Their main functions are controlled/ managed by a set of biological signals sent from central nervous system( through an interface). So the nervous system is an interface which your body uses to interact with your limbs. The &amp;quot;limbs&amp;quot; is a well architected class. The &amp;quot;legs&amp;quot; has a subclass which contains &amp;quot;left leg&amp;quot; and &amp;quot;Right leg&amp;quot;. The &amp;quot;legs&amp;quot; is being re-used to create the left leg and right leg by slightly changing the properties of it. If the &amp;quot;legs&amp;quot; owns attributes like length, color of skin etc, then the subclass, which contains &amp;quot;left leg&amp;quot; and &amp;quot;right leg&amp;quot; in this case, automatically inherit these attributes( that is called inheritance).&lt;br /&gt;
&lt;br /&gt;
We could code in object-oriented paradigm as:&lt;br /&gt;
&lt;br /&gt;
  class Limbs  /*define a class of limbs*/&lt;br /&gt;
    def initialize(limbs,length,colorofskin)&lt;br /&gt;
    @limbs=limbs&lt;br /&gt;
    @length=length&lt;br /&gt;
    @colorofskin=colorofskin&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  limbs=Limbs.new(&amp;quot;legs&amp;quot;,&amp;quot;100cm&amp;quot;,&amp;quot;white&amp;quot;)  /*create a new object in class &amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
  class Legs&amp;lt;Limbs   /*create a subclass &amp;quot;Legs&amp;quot;,which belong to class&amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
    def initialize(legs,length,colorofskin)&lt;br /&gt;
      super(length,colorofskin)&lt;br /&gt;
      @legs=legs&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
  legs=legs.new(&amp;quot;left leg&amp;quot;) /*create a new object in class of &amp;quot;Legs&amp;quot;*/&lt;br /&gt;
&lt;br /&gt;
== Features of Object-oriented Programming ==&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]. A programmer can simply create a new object that inherits many of its features from super-class. And also, they can overwrite existing operations or add new ones.This makes object-oriented programs easier to modify.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation].This refers to hiding the internal representation of the object from the outside view. You can hide unnecessary implementation details from the object user. One of the benefits of encapsulation is data protection.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism].This allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Consider the operator '+', for numbers it will generate the sum, but for strings it will produce a third string which concatenates the input strings.&lt;br /&gt;
&lt;br /&gt;
== Advantages of Object-oriented Programming ==&lt;br /&gt;
* Simplicity: we use software objects to simulate real world objects, so the complexity is reduced and the program structure is very clear.&lt;br /&gt;
* Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.&lt;br /&gt;
* Modifiability: programmers can easily make minor changes in the data representation or operations in an OOP. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.&lt;br /&gt;
* Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.&lt;br /&gt;
* Maintainability: objects can be maintained separately, making locating and fixing problems easier.&lt;br /&gt;
* Re-usability: objects can be reused in different programs.&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
In object-oriented world, data and operations are grouped together into modular units called objects and we combine objects into structured networks to form a program. The results are depend on arguments and objects' state at method invocation time. While in functional world, the basic elements are variables in the mathematical sense and functions in the mathematical sense. Functional programming can reduce side-effects. If there is no side-effects, it means your can apply the function at anywhere freely. No matter how you apply this function, the same input arguments produce the same results.&lt;br /&gt;
&lt;br /&gt;
According to above-mentioned information, we can perform functional programming on an object-oriented programming language because:&lt;br /&gt;
1). object can have constant state &lt;br /&gt;
2). method can depend only on its arguments and context available at method definition time&lt;br /&gt;
&lt;br /&gt;
Combining both these paradigms not only provide us a robust design structure, but also enable the programmers to develop solutions to complex problems quickly and effectively. One of the cornerstone of mixing functional and object-oriented code is treating functions as objects.It means that we can pass functions as arguments, store it and return them from other functions. This is highly useful in an user interface code where it can be used as call back functions which gets called when an event occurs(event driven programming).&lt;br /&gt;
&lt;br /&gt;
Some of the basic features of Functional Programming which can be combined with Object Oriented paradigm are:&lt;br /&gt;
&lt;br /&gt;
* Lambda Calculus&lt;br /&gt;
* Currying&lt;br /&gt;
* Powerful pattern matching&lt;br /&gt;
&lt;br /&gt;
Let us now understand how each of the above feature of Functional language fits in the Object Oriented paradigm.&lt;br /&gt;
&lt;br /&gt;
=== Lambda Calculus ===&lt;br /&gt;
Lambda calculus is the most critical basis of functional programming. A lambda expression is an anonymous expression that contain expressions and statements.Each expression stands for a function with one parameter. &lt;br /&gt;
&lt;br /&gt;
Let consider the following function:&lt;br /&gt;
&lt;br /&gt;
  def f(x)&lt;br /&gt;
  return x**2 &lt;br /&gt;
  print f(4)&lt;br /&gt;
&lt;br /&gt;
We can use a lambda calculus to compute this expression without assigning it to a variable: &lt;br /&gt;
&lt;br /&gt;
  (lambda x:x**x)(4)  &lt;br /&gt;
&lt;br /&gt;
We can see that these two code snippets have the same results. It is more concise and flexible to define with lambda.&lt;br /&gt;
The above is a pure functional approach. In order to make code more state-less and concise, lambdas can be embedded inside the object-oriented language. The below code in Python demonstrates the use of lambda in a closure:&lt;br /&gt;
&lt;br /&gt;
  def fun(x):&lt;br /&gt;
    return x%3==0&lt;br /&gt;
    str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
    filter(fun,str)&lt;br /&gt;
&lt;br /&gt;
The above code works to find numbers which are divisible by 3.&lt;br /&gt;
We can simplify the code by the use of lambda as following:&lt;br /&gt;
&lt;br /&gt;
  str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
  print filter(lambda x: x%3==0, str)&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
A number of programming languages support mixing of both functional and object-oriented code. Three of these (Scala, Ruby, and Conjure), are described in more detail below.&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky. It has a number of features.&lt;br /&gt;
&lt;br /&gt;
==== Statically Typed ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] belongs to the family of languages which encode the type information of each and every variable in the generated code. The compiler makes sure you are not doing something incorrectly. For example, lets consider the following example of code where the type is not encoded,&lt;br /&gt;
&lt;br /&gt;
In [http://www.ruby-lang.org/en/ Ruby],&lt;br /&gt;
   irb(main):001:0&amp;gt; str=&amp;quot;Hello World&amp;quot;&lt;br /&gt;
    =&amp;gt; &amp;quot;Hello World&amp;quot;&lt;br /&gt;
    irb(main):002:0&amp;gt; puts str.class&lt;br /&gt;
    String&lt;br /&gt;
    irb(main):003:0&amp;gt; str=123&lt;br /&gt;
    =&amp;gt; 123&lt;br /&gt;
    irb(main):004:0&amp;gt; puts str.class&lt;br /&gt;
    Fixnum&lt;br /&gt;
&lt;br /&gt;
In the above example, first we define 'str' variable to be of type String and then as a number. So basically, no type information is associated with the variable at any point in the program. Hence we can easily reassociate that variable with an object/instance&lt;br /&gt;
of a different type. This is a feature of all dynamically typed languages(like Ruby, Python, Clojure). However most of the statically typed languages such as Scala, Java, C/C++ do not allow you do so. In [http://www.scala-lang.org/ Scala],&lt;br /&gt;
&lt;br /&gt;
  scala&amp;gt; var str=&amp;quot;Hello World&amp;quot;&lt;br /&gt;
  str: java.lang.String = Hello World&lt;br /&gt;
  scala&amp;gt; str=123&lt;br /&gt;
  &amp;lt;console&amp;gt;:6: error: type mismatch;&lt;br /&gt;
   found   : Int(123)&lt;br /&gt;
   required: java.lang.String&lt;br /&gt;
         str=123&lt;br /&gt;
&lt;br /&gt;
==== Mixed paradigm ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object oriented and functional programming. How can this happen? Functional world advocates immutability but object oriented world is all about state and how do you mutate it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . Roughly translating the above line to Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as below&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks so much simpler and less verbose. Even though the above example shows immutable collection example, scala also provides mutable collection and object types under the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As it can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So its the best of both worlds. Another part of functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
==== Sophisticated Syntax/Features ====&lt;br /&gt;
Sophisticated syntax and features are present in other functional languages like Haskell, (O)Caml and Erlang. Consider the following example,&lt;br /&gt;
&lt;br /&gt;
   val name = &amp;quot;Jackie Chan&amp;quot;&lt;br /&gt;
   println(name.getClass) //prints out String.&lt;br /&gt;
&lt;br /&gt;
Previously we saw that [http://www.scala-lang.org/ Scala] is a statically typed language and yet in the above example we don't specify what type &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; is. In Java, you would type in the following:&lt;br /&gt;
&lt;br /&gt;
 String name = &amp;quot;Jackie Chan&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In Java you specify what type the name variable is, but the [http://www.scala-lang.org/ scala] compiler can automatically detect the type of the variable even if you don't specify it. Consider the following example,&lt;br /&gt;
&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
 val persons = List(&lt;br /&gt;
                        Person(&amp;quot;Jackie Chan&amp;quot;, 51), Person(&amp;quot;Jet Li&amp;quot;, 41),&lt;br /&gt;
                        Person(&amp;quot;RajniKanth&amp;quot;, 51), Person(&amp;quot;Kamal Hasan&amp;quot;, 44),&lt;br /&gt;
                        Person(&amp;quot;Martin Odersky&amp;quot;, 18), Person(&amp;quot;Steve Yegge&amp;quot;, 23))&lt;br /&gt;
 //notice that you don't have to use 'new' keyword to create new instances. This is taken care of by the companion objects.&lt;br /&gt;
&lt;br /&gt;
The above lines of code create a list with 6 different persons(An immutable list)&lt;br /&gt;
&lt;br /&gt;
Now, just like ruby, scala supports the concepts of [http://en.wikipedia.org/wiki/Closure_(computer_science) closure]. Let's see what it is.&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( { p: Person =&amp;gt; p.age == 3})&lt;br /&gt;
&lt;br /&gt;
In the above set of lines, the code within the '{ }' brackets is a function's body. The compiler created a function which takes a single argument and returns either true or false. &lt;br /&gt;
&lt;br /&gt;
==== A Scalable Language ====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. This feature is often called as [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching] because you are splitting open the class and adding/overriding methods (in)|(to) the class. Often this leads to unexpected behavior at runtime because, other libraries including into build path may depend on some methods which you changed. Scala provides yet another feature called implicits.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Ruby is another language that, like Scala, supports mixing functional and object-oriented code. It is a dynamically typed Object-Oriented Language which supports multiple programming paradigms, including functional, object-oriented, imperative and reflective. In Ruby, everything is an object, every bit of information and code can have its own properties and actions. However, Ruby’s blocks can be functional. A Ruby programmer can attach a closure to any method, which generates a functional block inside an object oriented code. A closure is a piece of code that can access the lexical environment of its definition [http://www.ruby-lang.org/en/ 11].&lt;br /&gt;
&lt;br /&gt;
==== Ruby Mixing example ====&lt;br /&gt;
&lt;br /&gt;
Consider the following code snippet in Ruby which uses Object Oriented concepts like Classes and functional programming concepts like lambda.&lt;br /&gt;
&lt;br /&gt;
 class Multiply&lt;br /&gt;
   def initialize(n)&lt;br /&gt;
     @block = lambda {|a| n * a}&lt;br /&gt;
   end&lt;br /&gt;
   def mul(a)&lt;br /&gt;
     @block.call a&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 twoMultiplier = Multiply.new 2                     &lt;br /&gt;
 puts twoMultiplier.mul(6)&lt;br /&gt;
&lt;br /&gt;
Here,'''''@block''''' is a closure. When we call the class ''Multiply'' using '''''twoAdder = Multiply.new 2''''' ,the ''initialize'' method is called by passing the parameter 2. Here n=2 binds itself to the block. So @block will be 2*a, that is,the closure remembers the parameter with which the initialize method was called even after the initialize method exits.  &lt;br /&gt;
&lt;br /&gt;
This value is used when the block is called in the add method.  &lt;br /&gt;
Thus,'''''twoMultiplier.mul(6)''''' will return 2*6 = 12&lt;br /&gt;
&lt;br /&gt;
==== Functional Style Coding in Ruby Blocks ====&lt;br /&gt;
&lt;br /&gt;
Blocks are basically nameless functions which can be passed to a function and then that function can invoke the passed in nameless function. This is a common style called [http://en.wikipedia.org/wiki/Higher-order_function higher order functions] among languages that handle functions as first class objects. Basically blocks can be designed for loop abstraction and lets the user to design their own way of iterating the values, thereby hiding the implementation details. &lt;br /&gt;
For example, if we want to iterate backwards from the end to the beginning without revealing its internal implementations, we could implement the loop logic inside the block and pass it to a method or function.&lt;br /&gt;
&lt;br /&gt;
Here is a [http://www.ruby-lang.org/en/ Ruby] implementation of block:&lt;br /&gt;
 &lt;br /&gt;
 def printlist(array,&amp;amp;reverse)&lt;br /&gt;
    array.each do |element|&lt;br /&gt;
       puts &amp;quot;array element: #{element}&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
    reverse.call(array)   /* Here it prints the reverse implementation of list*/&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
 printlist([1,2,3,4,5,6]) { |array| &lt;br /&gt;
   array.reverse.each do |element| &lt;br /&gt;
     puts &amp;quot;array element: #{element}&amp;quot; &lt;br /&gt;
   end &lt;br /&gt;
 }&lt;br /&gt;
The statements between { } is a block and it gets called by &amp;lt;code&amp;gt;reverse.call(array)&amp;lt;/code&amp;gt;within the printlist method.&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63228</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63228"/>
		<updated>2012-09-09T22:24:18Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Examples of Mixing */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and data is immutable****. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily. &lt;br /&gt;
&lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-oriented Programming =&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm organized around interacting &amp;quot;objects&amp;quot;(usually instances of a class) rather than &amp;quot;actions&amp;quot; and data rather than logic. A basic principle of OOP is that a program consists of a list of subroutines which can perform individually. &lt;br /&gt;
&lt;br /&gt;
An object-oriented programming language provides support for the following object-oriented concepts--object, class, interface and inheritance. To illustrate this idea clearly and vividly let's review the following example-- your limbs. The &amp;quot;Limbs&amp;quot; is a class. Your body has two objects of type &amp;quot;limbs&amp;quot;, named arms and legs. Their main functions are controlled/ managed by a set of biological signals sent from central nervous system( through an interface). So the nervous system is an interface which your body uses to interact with your limbs. The &amp;quot;limbs&amp;quot; is a well architected class. The &amp;quot;legs&amp;quot; has a subclass which contains &amp;quot;left leg&amp;quot; and &amp;quot;Right leg&amp;quot;. The &amp;quot;legs&amp;quot; is being re-used to create the left leg and right leg by slightly changing the properties of it. If the &amp;quot;legs&amp;quot; owns attributes like length, color of skin etc, then the subclass, which contains &amp;quot;left leg&amp;quot; and &amp;quot;right leg&amp;quot; in this case, automatically inherit these attributes( that is called inheritance).&lt;br /&gt;
&lt;br /&gt;
We could code in object-oriented paradigm as:&lt;br /&gt;
&lt;br /&gt;
  class Limbs  /*define a class of limbs*/&lt;br /&gt;
    def initialize(limbs,length,colorofskin)&lt;br /&gt;
    @limbs=limbs&lt;br /&gt;
    @length=length&lt;br /&gt;
    @colorofskin=colorofskin&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  limbs=Limbs.new(&amp;quot;legs&amp;quot;,&amp;quot;100cm&amp;quot;,&amp;quot;white&amp;quot;)  /*create a new object in class &amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
  class Legs&amp;lt;Limbs   /*create a subclass &amp;quot;Legs&amp;quot;,which belong to class&amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
    def initialize(legs,length,colorofskin)&lt;br /&gt;
      super(length,colorofskin)&lt;br /&gt;
      @legs=legs&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
  legs=legs.new(&amp;quot;left leg&amp;quot;) /*create a new object in class of &amp;quot;Legs&amp;quot;*/&lt;br /&gt;
&lt;br /&gt;
== Features of Object-oriented Programming ==&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]. A programmer can simply create a new object that inherits many of its features from super-class. And also, they can overwrite existing operations or add new ones.This makes object-oriented programs easier to modify.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation].This refers to hiding the internal representation of the object from the outside view. You can hide unnecessary implementation details from the object user. One of the benefits of encapsulation is data protection.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism].This allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Consider the operator '+', for numbers it will generate the sum, but for strings it will produce a third string which concatenates the input strings.&lt;br /&gt;
&lt;br /&gt;
== Advantages of Object-oriented Programming ==&lt;br /&gt;
* Simplicity: we use software objects to simulate real world objects, so the complexity is reduced and the program structure is very clear.&lt;br /&gt;
* Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.&lt;br /&gt;
* Modifiability: programmers can easily make minor changes in the data representation or operations in an OOP. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.&lt;br /&gt;
* Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.&lt;br /&gt;
* Maintainability: objects can be maintained separately, making locating and fixing problems easier.&lt;br /&gt;
* Re-usability: objects can be reused in different programs.&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
In object-oriented world, data and operations are grouped together into modular units called objects and we combine objects into structured networks to form a program. The results are depend on arguments and objects' state at method invocation time. While in functional world, the basic elements are variables in the mathematical sense and functions in the mathematical sense. Functional programming can reduce side-effects. If there is no side-effects, it means your can apply the function at anywhere freely. No matter how you apply this function, the same input arguments produce the same results.&lt;br /&gt;
&lt;br /&gt;
According to above-mentioned information, we can perform functional programming on an object-oriented programming language because:&lt;br /&gt;
1). object can have constant state &lt;br /&gt;
2). method can depend only on its arguments and context available at method definition time&lt;br /&gt;
&lt;br /&gt;
Combining both these paradigms not only provide us a robust design structure, but also enable the programmers to develop solutions to complex problems quickly and effectively. One of the cornerstone of mixing functional and object-oriented code is treating functions as objects.It means that we can pass functions as arguments, store it and return them from other functions. This is highly useful in an user interface code where it can be used as call back functions which gets called when an event occurs(event driven programming).&lt;br /&gt;
&lt;br /&gt;
Some of the basic features of Functional Programming which can be combined with Object Oriented paradigm are:&lt;br /&gt;
&lt;br /&gt;
* Lambda Calculus&lt;br /&gt;
* Currying&lt;br /&gt;
* Powerful pattern matching&lt;br /&gt;
&lt;br /&gt;
Let us now understand how each of the above feature of Functional language fits in the Object Oriented paradigm.&lt;br /&gt;
&lt;br /&gt;
=== Lambda Calculus ===&lt;br /&gt;
Lambda calculus is the most critical basis of functional programming. A lambda expression is an anonymous expression that contain expressions and statements.Each expression stands for a function with one parameter. &lt;br /&gt;
&lt;br /&gt;
Let consider the following function:&lt;br /&gt;
&lt;br /&gt;
  def f(x)&lt;br /&gt;
  return x**2 &lt;br /&gt;
  print f(4)&lt;br /&gt;
&lt;br /&gt;
We can use a lambda calculus to compute this expression without assigning it to a variable: &lt;br /&gt;
&lt;br /&gt;
  (lambda x:x**x)(4)  &lt;br /&gt;
&lt;br /&gt;
We can see that these two code snippets have the same results. It is more concise and flexible to define with lambda.&lt;br /&gt;
The above is a pure functional approach. In order to make code more state-less and concise, lambdas can be embedded inside the object-oriented language. The below code in Python demonstrates the use of lambda in a closure:&lt;br /&gt;
&lt;br /&gt;
  def fun(x):&lt;br /&gt;
    return x%3==0&lt;br /&gt;
    str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
    filter(fun,str)&lt;br /&gt;
&lt;br /&gt;
The above code works to find numbers which are divisible by 3.&lt;br /&gt;
We can simplify the code by the use of lambda as following:&lt;br /&gt;
&lt;br /&gt;
  str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
  print filter(lambda x: x%3==0, str)&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
A number of programming languages support mixing of both functional and object-oriented code. Three of these (Scala, Ruby, and Conjure), are described in more detail below.&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky. It has a number of features.&lt;br /&gt;
&lt;br /&gt;
==== Statically Typed ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] belongs to the family of languages which encode the type information of each and every variable in the generated code. The compiler makes sure you are not doing something incorrectly. For example, lets consider the following example of code where the type is not encoded,&lt;br /&gt;
&lt;br /&gt;
In [http://www.ruby-lang.org/en/ Ruby],&lt;br /&gt;
   irb(main):001:0&amp;gt; str=&amp;quot;Hello World&amp;quot;&lt;br /&gt;
    =&amp;gt; &amp;quot;Hello World&amp;quot;&lt;br /&gt;
    irb(main):002:0&amp;gt; puts str.class&lt;br /&gt;
    String&lt;br /&gt;
    irb(main):003:0&amp;gt; str=123&lt;br /&gt;
    =&amp;gt; 123&lt;br /&gt;
    irb(main):004:0&amp;gt; puts str.class&lt;br /&gt;
    Fixnum&lt;br /&gt;
&lt;br /&gt;
In the above example, first we define 'str' variable to be of type String and then as a number. So basically, no type information is associated with the variable at any point in the program. Hence we can easily reassociate that variable with an object/instance&lt;br /&gt;
of a different type. This is a feature of all dynamically typed languages(like Ruby, Python, Clojure). However most of the statically typed languages such as Scala, Java, C/C++ do not allow you do so. In [http://www.scala-lang.org/ Scala],&lt;br /&gt;
&lt;br /&gt;
  scala&amp;gt; var str=&amp;quot;Hello World&amp;quot;&lt;br /&gt;
  str: java.lang.String = Hello World&lt;br /&gt;
  scala&amp;gt; str=123&lt;br /&gt;
  &amp;lt;console&amp;gt;:6: error: type mismatch;&lt;br /&gt;
   found   : Int(123)&lt;br /&gt;
   required: java.lang.String&lt;br /&gt;
         str=123&lt;br /&gt;
&lt;br /&gt;
==== Mixed paradigm ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object oriented and functional programming. How can this happen? Functional world advocates immutability but object oriented world is all about state and how do you mutate it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . Roughly translating the above line to Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as below&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks so much simpler and less verbose. Even though the above example shows immutable collection example, scala also provides mutable collection and object types under the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As it can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So its the best of both worlds. Another part of functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
==== Sophisticated Syntax/Features ====&lt;br /&gt;
Sophisticated syntax and features are present in other functional languages like Haskell, (O)Caml and Erlang. Consider the following example,&lt;br /&gt;
&lt;br /&gt;
   val name = &amp;quot;Jackie Chan&amp;quot;&lt;br /&gt;
   println(name.getClass) //prints out String.&lt;br /&gt;
&lt;br /&gt;
Previously we saw that [http://www.scala-lang.org/ Scala] is a statically typed language and yet in the above example we don't specify what type &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; is. In Java, you would type in the following:&lt;br /&gt;
&lt;br /&gt;
 String name = &amp;quot;Jackie Chan&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In Java you specify what type the name variable is, but the [http://www.scala-lang.org/ scala] compiler can automatically detect the type of the variable even if you don't specify it. Consider the following example,&lt;br /&gt;
&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
 val persons = List(&lt;br /&gt;
                        Person(&amp;quot;Jackie Chan&amp;quot;, 51), Person(&amp;quot;Jet Li&amp;quot;, 41),&lt;br /&gt;
                        Person(&amp;quot;RajniKanth&amp;quot;, 51), Person(&amp;quot;Kamal Hasan&amp;quot;, 44),&lt;br /&gt;
                        Person(&amp;quot;Martin Odersky&amp;quot;, 18), Person(&amp;quot;Steve Yegge&amp;quot;, 23))&lt;br /&gt;
 //notice that you don't have to use 'new' keyword to create new instances. This is taken care of by the companion objects.&lt;br /&gt;
&lt;br /&gt;
The above lines of code create a list with 6 different persons(An immutable list)&lt;br /&gt;
&lt;br /&gt;
Now, just like ruby, scala supports the concepts of [http://en.wikipedia.org/wiki/Closure_(computer_science) closure]. Let's see what it is.&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( { p: Person =&amp;gt; p.age == 3})&lt;br /&gt;
&lt;br /&gt;
In the above set of lines, the code within the '{ }' brackets is a function's body. The compiler created a function which takes a single argument and returns either true or false. &lt;br /&gt;
&lt;br /&gt;
==== A Scalable Language ====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. This feature is often called as [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching] because you are splitting open the class and adding/overriding methods (in)|(to) the class. Often this leads to unexpected behavior at runtime because, other libraries including into build path may depend on some methods which you changed. Scala provides yet another feature called implicits.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Ruby is another language that, like Scala, supports mixing functional and object-oriented code. It is a dynamically typed Object-Oriented Language which supports multiple programming paradigms, including functional, object-oriented, imperative and reflective. In Ruby, everything is an object, every bit of information and code can have its own properties and actions. However, Ruby’s blocks can be functional. A Ruby programmer can attach a closure to any method, which generates a functional block inside an object oriented code. A closure is a piece of code that can access the lexical environment of its definition [http://www.ruby-lang.org/en/ 11].&lt;br /&gt;
&lt;br /&gt;
Consider the following code snippet in Ruby which uses Object Oriented concepts like Classes and functional programming concepts like lambda.&lt;br /&gt;
&lt;br /&gt;
 class Multiply&lt;br /&gt;
   def initialize(n)&lt;br /&gt;
     @block = lambda {|a| n * a}&lt;br /&gt;
   end&lt;br /&gt;
   def mul(a)&lt;br /&gt;
     @block.call a&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 twoMultiplier = Multiply.new 2                     &lt;br /&gt;
 puts twoMultiplier.mul(6)&lt;br /&gt;
&lt;br /&gt;
Here,'''''@block''''' is a closure. When we call the class ''Multiply'' using '''''twoAdder = Multiply.new 2''''' ,the ''initialize'' method is called by passing the parameter 2. Here n=2 binds itself to the block. So @block will be 2*a, that is,the closure remembers the parameter with which the initialize method was called even after the initialize method exits.  &lt;br /&gt;
&lt;br /&gt;
This value is used when the block is called in the add method.  &lt;br /&gt;
Thus,'''''twoMultiplier.mul(6)''''' will return 2*6 = 12&lt;br /&gt;
&lt;br /&gt;
Blocks are basically nameless functions which can be passed to a function and then that function can invoke the passed in nameless function. This is a common style called [http://en.wikipedia.org/wiki/Higher-order_function higher order functions] among languages that handle functions as first class objects. Basically blocks can be designed for loop abstraction and lets the user to design their own way of iterating the values, thereby hiding the implementation details. &lt;br /&gt;
For example, if we want to iterate backwards from the end to the beginning without revealing its internal implementations, we could implement the loop logic inside the block and pass it to a method or function.&lt;br /&gt;
&lt;br /&gt;
Here is a [http://www.ruby-lang.org/en/ Ruby] implementation of block:&lt;br /&gt;
 &lt;br /&gt;
 def printlist(array,&amp;amp;reverse)&lt;br /&gt;
    array.each do |element|&lt;br /&gt;
       puts &amp;quot;array element: #{element}&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
    reverse.call(array)   /* Here it prints the reverse implementation of list*/&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
 printlist([1,2,3,4,5,6]) { |array| &lt;br /&gt;
   array.reverse.each do |element| &lt;br /&gt;
     puts &amp;quot;array element: #{element}&amp;quot; &lt;br /&gt;
   end &lt;br /&gt;
 }&lt;br /&gt;
The statements between { } is a block and it gets called by &amp;lt;code&amp;gt;reverse.call(array)&amp;lt;/code&amp;gt;within the printlist method.&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63223</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63223"/>
		<updated>2012-09-09T22:20:18Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Scala */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and data is immutable****. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily. &lt;br /&gt;
&lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-oriented Programming =&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm organized around interacting &amp;quot;objects&amp;quot;(usually instances of a class) rather than &amp;quot;actions&amp;quot; and data rather than logic. A basic principle of OOP is that a program consists of a list of subroutines which can perform individually. &lt;br /&gt;
&lt;br /&gt;
An object-oriented programming language provides support for the following object-oriented concepts--object, class, interface and inheritance. To illustrate this idea clearly and vividly let's review the following example-- your limbs. The &amp;quot;Limbs&amp;quot; is a class. Your body has two objects of type &amp;quot;limbs&amp;quot;, named arms and legs. Their main functions are controlled/ managed by a set of biological signals sent from central nervous system( through an interface). So the nervous system is an interface which your body uses to interact with your limbs. The &amp;quot;limbs&amp;quot; is a well architected class. The &amp;quot;legs&amp;quot; has a subclass which contains &amp;quot;left leg&amp;quot; and &amp;quot;Right leg&amp;quot;. The &amp;quot;legs&amp;quot; is being re-used to create the left leg and right leg by slightly changing the properties of it. If the &amp;quot;legs&amp;quot; owns attributes like length, color of skin etc, then the subclass, which contains &amp;quot;left leg&amp;quot; and &amp;quot;right leg&amp;quot; in this case, automatically inherit these attributes( that is called inheritance).&lt;br /&gt;
&lt;br /&gt;
We could code in object-oriented paradigm as:&lt;br /&gt;
&lt;br /&gt;
  class Limbs  /*define a class of limbs*/&lt;br /&gt;
    def initialize(limbs,length,colorofskin)&lt;br /&gt;
    @limbs=limbs&lt;br /&gt;
    @length=length&lt;br /&gt;
    @colorofskin=colorofskin&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  limbs=Limbs.new(&amp;quot;legs&amp;quot;,&amp;quot;100cm&amp;quot;,&amp;quot;white&amp;quot;)  /*create a new object in class &amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
  class Legs&amp;lt;Limbs   /*create a subclass &amp;quot;Legs&amp;quot;,which belong to class&amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
    def initialize(legs,length,colorofskin)&lt;br /&gt;
      super(length,colorofskin)&lt;br /&gt;
      @legs=legs&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
  legs=legs.new(&amp;quot;left leg&amp;quot;) /*create a new object in class of &amp;quot;Legs&amp;quot;*/&lt;br /&gt;
&lt;br /&gt;
== Features of Object-oriented Programming ==&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]. A programmer can simply create a new object that inherits many of its features from super-class. And also, they can overwrite existing operations or add new ones.This makes object-oriented programs easier to modify.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation].This refers to hiding the internal representation of the object from the outside view. You can hide unnecessary implementation details from the object user. One of the benefits of encapsulation is data protection.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism].This allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Consider the operator '+', for numbers it will generate the sum, but for strings it will produce a third string which concatenates the input strings.&lt;br /&gt;
&lt;br /&gt;
== Advantages of Object-oriented Programming ==&lt;br /&gt;
* Simplicity: we use software objects to simulate real world objects, so the complexity is reduced and the program structure is very clear.&lt;br /&gt;
* Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.&lt;br /&gt;
* Modifiability: programmers can easily make minor changes in the data representation or operations in an OOP. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.&lt;br /&gt;
* Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.&lt;br /&gt;
* Maintainability: objects can be maintained separately, making locating and fixing problems easier.&lt;br /&gt;
* Re-usability: objects can be reused in different programs.&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
In object-oriented world, data and operations are grouped together into modular units called objects and we combine objects into structured networks to form a program. The results are depend on arguments and objects' state at method invocation time. While in functional world, the basic elements are variables in the mathematical sense and functions in the mathematical sense. Functional programming can reduce side-effects. If there is no side-effects, it means your can apply the function at anywhere freely. No matter how you apply this function, the same input arguments produce the same results.&lt;br /&gt;
&lt;br /&gt;
According to above-mentioned information, we can perform functional programming on an object-oriented programming language because:&lt;br /&gt;
1). object can have constant state &lt;br /&gt;
2). method can depend only on its arguments and context available at method definition time&lt;br /&gt;
&lt;br /&gt;
Combining both these paradigms not only provide us a robust design structure, but also enable the programmers to develop solutions to complex problems quickly and effectively. One of the cornerstone of mixing functional and object-oriented code is treating functions as objects.It means that we can pass functions as arguments, store it and return them from other functions. This is highly useful in an user interface code where it can be used as call back functions which gets called when an event occurs(event driven programming).&lt;br /&gt;
&lt;br /&gt;
Some of the basic features of Functional Programming which can be combined with Object Oriented paradigm are:&lt;br /&gt;
&lt;br /&gt;
* Lambda Calculus&lt;br /&gt;
* Currying&lt;br /&gt;
* Powerful pattern matching&lt;br /&gt;
&lt;br /&gt;
Let us now understand how each of the above feature of Functional language fits in the Object Oriented paradigm.&lt;br /&gt;
&lt;br /&gt;
=== Lambda Calculus ===&lt;br /&gt;
Lambda calculus is the most critical basis of functional programming. A lambda expression is an anonymous expression that contain expressions and statements.Each expression stands for a function with one parameter. &lt;br /&gt;
&lt;br /&gt;
Let consider the following function:&lt;br /&gt;
&lt;br /&gt;
  def f(x)&lt;br /&gt;
  return x**2 &lt;br /&gt;
  print f(4)&lt;br /&gt;
&lt;br /&gt;
We can use a lambda calculus to compute this expression without assigning it to a variable: &lt;br /&gt;
&lt;br /&gt;
  (lambda x:x**x)(4)  &lt;br /&gt;
&lt;br /&gt;
We can see that these two code snippets have the same results. It is more concise and flexible to define with lambda.&lt;br /&gt;
The above is a pure functional approach. In order to make code more state-less and concise, lambdas can be embedded inside the object-oriented language. The below code in Python demonstrates the use of lambda in a closure:&lt;br /&gt;
&lt;br /&gt;
  def fun(x):&lt;br /&gt;
    return x%3==0&lt;br /&gt;
    str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
    filter(fun,str)&lt;br /&gt;
&lt;br /&gt;
The above code works to find numbers which are divisible by 3.&lt;br /&gt;
We can simplify the code by the use of lambda as following:&lt;br /&gt;
&lt;br /&gt;
  str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
  print filter(lambda x: x%3==0, str)&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky. It has a number of features.&lt;br /&gt;
&lt;br /&gt;
==== Statically Typed ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] belongs to the family of languages which encode the type information of each and every variable in the generated code. The compiler makes sure you are not doing something incorrectly. For example, lets consider the following example of code where the type is not encoded,&lt;br /&gt;
&lt;br /&gt;
In [http://www.ruby-lang.org/en/ Ruby],&lt;br /&gt;
   irb(main):001:0&amp;gt; str=&amp;quot;Hello World&amp;quot;&lt;br /&gt;
    =&amp;gt; &amp;quot;Hello World&amp;quot;&lt;br /&gt;
    irb(main):002:0&amp;gt; puts str.class&lt;br /&gt;
    String&lt;br /&gt;
    irb(main):003:0&amp;gt; str=123&lt;br /&gt;
    =&amp;gt; 123&lt;br /&gt;
    irb(main):004:0&amp;gt; puts str.class&lt;br /&gt;
    Fixnum&lt;br /&gt;
&lt;br /&gt;
In the above example, first we define 'str' variable to be of type String and then as a number. So basically, no type information is associated with the variable at any point in the program. Hence we can easily reassociate that variable with an object/instance&lt;br /&gt;
of a different type. This is a feature of all dynamically typed languages(like Ruby, Python, Clojure). However most of the statically typed languages such as Scala, Java, C/C++ do not allow you do so. In [http://www.scala-lang.org/ Scala],&lt;br /&gt;
&lt;br /&gt;
  scala&amp;gt; var str=&amp;quot;Hello World&amp;quot;&lt;br /&gt;
  str: java.lang.String = Hello World&lt;br /&gt;
  scala&amp;gt; str=123&lt;br /&gt;
  &amp;lt;console&amp;gt;:6: error: type mismatch;&lt;br /&gt;
   found   : Int(123)&lt;br /&gt;
   required: java.lang.String&lt;br /&gt;
         str=123&lt;br /&gt;
&lt;br /&gt;
==== Mixed paradigm ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object oriented and functional programming. How can this happen? Functional world advocates immutability but object oriented world is all about state and how do you mutate it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . Roughly translating the above line to Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as below&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks so much simpler and less verbose. Even though the above example shows immutable collection example, scala also provides mutable collection and object types under the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As it can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So its the best of both worlds. Another part of functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
==== Sophisticated Syntax/Features ====&lt;br /&gt;
Sophisticated syntax and features are present in other functional languages like Haskell, (O)Caml and Erlang. Consider the following example,&lt;br /&gt;
&lt;br /&gt;
   val name = &amp;quot;Jackie Chan&amp;quot;&lt;br /&gt;
   println(name.getClass) //prints out String.&lt;br /&gt;
&lt;br /&gt;
Previously we saw that [http://www.scala-lang.org/ Scala] is a statically typed language and yet in the above example we don't specify what type &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; is. In Java, you would type in the following:&lt;br /&gt;
&lt;br /&gt;
 String name = &amp;quot;Jackie Chan&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In Java you specify what type the name variable is, but the [http://www.scala-lang.org/ scala] compiler can automatically detect the type of the variable even if you don't specify it. Consider the following example,&lt;br /&gt;
&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
 val persons = List(&lt;br /&gt;
                        Person(&amp;quot;Jackie Chan&amp;quot;, 51), Person(&amp;quot;Jet Li&amp;quot;, 41),&lt;br /&gt;
                        Person(&amp;quot;RajniKanth&amp;quot;, 51), Person(&amp;quot;Kamal Hasan&amp;quot;, 44),&lt;br /&gt;
                        Person(&amp;quot;Martin Odersky&amp;quot;, 18), Person(&amp;quot;Steve Yegge&amp;quot;, 23))&lt;br /&gt;
 //notice that you don't have to use 'new' keyword to create new instances. This is taken care of by the companion objects.&lt;br /&gt;
&lt;br /&gt;
The above lines of code create a list with 6 different persons(An immutable list)&lt;br /&gt;
&lt;br /&gt;
Now, just like ruby, scala supports the concepts of [http://en.wikipedia.org/wiki/Closure_(computer_science) closure]. Let's see what it is.&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( { p: Person =&amp;gt; p.age == 3})&lt;br /&gt;
&lt;br /&gt;
In the above set of lines, the code within the '{ }' brackets is a function's body. The compiler created a function which takes a single argument and returns either true or false. &lt;br /&gt;
&lt;br /&gt;
==== A Scalable Language ====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. This feature is often called as [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching] because you are splitting open the class and adding/overriding methods (in)|(to) the class. Often this leads to unexpected behavior at runtime because, other libraries including into build path may depend on some methods which you changed. Scala provides yet another feature called implicits.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Ruby is a dynamically typed Object Oriented Language which supports multiple programming paradigms, including functional, object-oriented, imperative and reflective. In Ruby, everything is an object, every bit of information and code can have its own properties and actions. However, Ruby’s blocks can be functional. A Ruby programmer can attach a closure to any method, which generates a functional block inside an object oriented code. A closure is a piece of code that can access the lexical environment of its definition [http://www.ruby-lang.org/en/ 11].&lt;br /&gt;
&lt;br /&gt;
Consider the following code snippet in Ruby which uses Object Oriented concepts like Classes and functional programming concepts like lambda.&lt;br /&gt;
&lt;br /&gt;
 class Multiply&lt;br /&gt;
   def initialize(n)&lt;br /&gt;
     @block = lambda {|a| n * a}&lt;br /&gt;
   end&lt;br /&gt;
   def mul(a)&lt;br /&gt;
     @block.call a&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 twoMultiplier = Multiply.new 2                     &lt;br /&gt;
 puts twoMultiplier.mul(6)&lt;br /&gt;
&lt;br /&gt;
Here,'''''@block''''' is a closure. When we call the class ''Multiply'' using '''''twoAdder = Multiply.new 2''''' ,the ''initialize'' method is called by passing the parameter 2. Here n=2 binds itself to the block. So @block will be 2*a, that is,the closure remembers the parameter with which the initialize method was called even after the initialize method exits.  &lt;br /&gt;
&lt;br /&gt;
This value is used when the block is called in the add method.  &lt;br /&gt;
Thus,'''''twoMultiplier.mul(6)''''' will return 2*6 = 12&lt;br /&gt;
&lt;br /&gt;
Blocks are basically nameless functions which can be passed to a function and then that function can invoke the passed in nameless function. This is a common style called [http://en.wikipedia.org/wiki/Higher-order_function higher order functions] among languages that handle functions as first class objects. Basically blocks can be designed for loop abstraction and lets the user to design their own way of iterating the values, thereby hiding the implementation details. &lt;br /&gt;
For example, if we want to iterate backwards from the end to the beginning without revealing its internal implementations, we could implement the loop logic inside the block and pass it to a method or function.&lt;br /&gt;
&lt;br /&gt;
Here is a [http://www.ruby-lang.org/en/ Ruby] implementation of block:&lt;br /&gt;
 &lt;br /&gt;
 def printlist(array,&amp;amp;reverse)&lt;br /&gt;
    array.each do |element|&lt;br /&gt;
       puts &amp;quot;array element: #{element}&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
    reverse.call(array)   /* Here it prints the reverse implementation of list*/&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
 printlist([1,2,3,4,5,6]) { |array| &lt;br /&gt;
   array.reverse.each do |element| &lt;br /&gt;
     puts &amp;quot;array element: #{element}&amp;quot; &lt;br /&gt;
   end &lt;br /&gt;
 }&lt;br /&gt;
The statements between { } is a block and it gets called by &amp;lt;code&amp;gt;reverse.call(array)&amp;lt;/code&amp;gt;within the printlist method.&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63222</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63222"/>
		<updated>2012-09-09T22:18:12Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: Added Ruby section and modified Scala section&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and data is immutable****. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily. &lt;br /&gt;
&lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-oriented Programming =&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] (OOP) is a programming paradigm organized around interacting &amp;quot;objects&amp;quot;(usually instances of a class) rather than &amp;quot;actions&amp;quot; and data rather than logic. A basic principle of OOP is that a program consists of a list of subroutines which can perform individually. &lt;br /&gt;
&lt;br /&gt;
An object-oriented programming language provides support for the following object-oriented concepts--object, class, interface and inheritance. To illustrate this idea clearly and vividly let's review the following example-- your limbs. The &amp;quot;Limbs&amp;quot; is a class. Your body has two objects of type &amp;quot;limbs&amp;quot;, named arms and legs. Their main functions are controlled/ managed by a set of biological signals sent from central nervous system( through an interface). So the nervous system is an interface which your body uses to interact with your limbs. The &amp;quot;limbs&amp;quot; is a well architected class. The &amp;quot;legs&amp;quot; has a subclass which contains &amp;quot;left leg&amp;quot; and &amp;quot;Right leg&amp;quot;. The &amp;quot;legs&amp;quot; is being re-used to create the left leg and right leg by slightly changing the properties of it. If the &amp;quot;legs&amp;quot; owns attributes like length, color of skin etc, then the subclass, which contains &amp;quot;left leg&amp;quot; and &amp;quot;right leg&amp;quot; in this case, automatically inherit these attributes( that is called inheritance).&lt;br /&gt;
&lt;br /&gt;
We could code in object-oriented paradigm as:&lt;br /&gt;
&lt;br /&gt;
  class Limbs  /*define a class of limbs*/&lt;br /&gt;
    def initialize(limbs,length,colorofskin)&lt;br /&gt;
    @limbs=limbs&lt;br /&gt;
    @length=length&lt;br /&gt;
    @colorofskin=colorofskin&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  limbs=Limbs.new(&amp;quot;legs&amp;quot;,&amp;quot;100cm&amp;quot;,&amp;quot;white&amp;quot;)  /*create a new object in class &amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
  class Legs&amp;lt;Limbs   /*create a subclass &amp;quot;Legs&amp;quot;,which belong to class&amp;quot;Limbs&amp;quot;*/&lt;br /&gt;
    def initialize(legs,length,colorofskin)&lt;br /&gt;
      super(length,colorofskin)&lt;br /&gt;
      @legs=legs&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
  legs=legs.new(&amp;quot;left leg&amp;quot;) /*create a new object in class of &amp;quot;Legs&amp;quot;*/&lt;br /&gt;
&lt;br /&gt;
== Features of Object-oriented Programming ==&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]. A programmer can simply create a new object that inherits many of its features from super-class. And also, they can overwrite existing operations or add new ones.This makes object-oriented programs easier to modify.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation].This refers to hiding the internal representation of the object from the outside view. You can hide unnecessary implementation details from the object user. One of the benefits of encapsulation is data protection.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism].This allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects. Consider the operator '+', for numbers it will generate the sum, but for strings it will produce a third string which concatenates the input strings.&lt;br /&gt;
&lt;br /&gt;
== Advantages of Object-oriented Programming ==&lt;br /&gt;
* Simplicity: we use software objects to simulate real world objects, so the complexity is reduced and the program structure is very clear.&lt;br /&gt;
* Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.&lt;br /&gt;
* Modifiability: programmers can easily make minor changes in the data representation or operations in an OOP. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.&lt;br /&gt;
* Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.&lt;br /&gt;
* Maintainability: objects can be maintained separately, making locating and fixing problems easier.&lt;br /&gt;
* Re-usability: objects can be reused in different programs.&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
In object-oriented world, data and operations are grouped together into modular units called objects and we combine objects into structured networks to form a program. The results are depend on arguments and objects' state at method invocation time. While in functional world, the basic elements are variables in the mathematical sense and functions in the mathematical sense. Functional programming can reduce side-effects. If there is no side-effects, it means your can apply the function at anywhere freely. No matter how you apply this function, the same input arguments produce the same results.&lt;br /&gt;
&lt;br /&gt;
According to above-mentioned information, we can perform functional programming on an object-oriented programming language because:&lt;br /&gt;
1). object can have constant state &lt;br /&gt;
2). method can depend only on its arguments and context available at method definition time&lt;br /&gt;
&lt;br /&gt;
Combining both these paradigms not only provide us a robust design structure, but also enable the programmers to develop solutions to complex problems quickly and effectively. One of the cornerstone of mixing functional and object-oriented code is treating functions as objects.It means that we can pass functions as arguments, store it and return them from other functions. This is highly useful in an user interface code where it can be used as call back functions which gets called when an event occurs(event driven programming).&lt;br /&gt;
&lt;br /&gt;
Some of the basic features of Functional Programming which can be combined with Object Oriented paradigm are:&lt;br /&gt;
&lt;br /&gt;
* Lambda Calculus&lt;br /&gt;
* Currying&lt;br /&gt;
* Powerful pattern matching&lt;br /&gt;
&lt;br /&gt;
Let us now understand how each of the above feature of Functional language fits in the Object Oriented paradigm.&lt;br /&gt;
&lt;br /&gt;
=== Lambda Calculus ===&lt;br /&gt;
Lambda calculus is the most critical basis of functional programming. A lambda expression is an anonymous expression that contain expressions and statements.Each expression stands for a function with one parameter. &lt;br /&gt;
&lt;br /&gt;
Let consider the following function:&lt;br /&gt;
&lt;br /&gt;
  def f(x)&lt;br /&gt;
  return x**2 &lt;br /&gt;
  print f(4)&lt;br /&gt;
&lt;br /&gt;
We can use a lambda calculus to compute this expression without assigning it to a variable: &lt;br /&gt;
&lt;br /&gt;
  (lambda x:x**x)(4)  &lt;br /&gt;
&lt;br /&gt;
We can see that these two code snippets have the same results. It is more concise and flexible to define with lambda.&lt;br /&gt;
The above is a pure functional approach. In order to make code more state-less and concise, lambdas can be embedded inside the object-oriented language. The below code in Python demonstrates the use of lambda in a closure:&lt;br /&gt;
&lt;br /&gt;
  def fun(x):&lt;br /&gt;
    return x%3==0&lt;br /&gt;
    str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
    filter(fun,str)&lt;br /&gt;
&lt;br /&gt;
The above code works to find numbers which are divisible by 3.&lt;br /&gt;
We can simplify the code by the use of lambda as following:&lt;br /&gt;
&lt;br /&gt;
  str=[2, 18, 9, 22, 17, 24, 8, 12, 27]&lt;br /&gt;
  print filter(lambda x: x%3==0, str)&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky.&lt;br /&gt;
&lt;br /&gt;
==== Features ====&lt;br /&gt;
===== Statically Typed =====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] belongs to the family of languages which encode the type information of each and every variable in the generated code. The compiler makes sure you are not doing something incorrectly. For example, lets consider the following example of code where the type is not encoded,&lt;br /&gt;
&lt;br /&gt;
In [http://www.ruby-lang.org/en/ Ruby],&lt;br /&gt;
   irb(main):001:0&amp;gt; str=&amp;quot;Hello World&amp;quot;&lt;br /&gt;
    =&amp;gt; &amp;quot;Hello World&amp;quot;&lt;br /&gt;
    irb(main):002:0&amp;gt; puts str.class&lt;br /&gt;
    String&lt;br /&gt;
    irb(main):003:0&amp;gt; str=123&lt;br /&gt;
    =&amp;gt; 123&lt;br /&gt;
    irb(main):004:0&amp;gt; puts str.class&lt;br /&gt;
    Fixnum&lt;br /&gt;
&lt;br /&gt;
In the above example, first we define 'str' variable to be of type String and then as a number. So basically, no type information is associated with the variable at any point in the program. Hence we can easily reassociate that variable with an object/instance&lt;br /&gt;
of a different type. This is a feature of all dynamically typed languages(like Ruby, Python, Clojure). However most of the statically typed languages such as Scala, Java, C/C++ do not allow you do so. In [http://www.scala-lang.org/ Scala],&lt;br /&gt;
&lt;br /&gt;
  scala&amp;gt; var str=&amp;quot;Hello World&amp;quot;&lt;br /&gt;
  str: java.lang.String = Hello World&lt;br /&gt;
  scala&amp;gt; str=123&lt;br /&gt;
  &amp;lt;console&amp;gt;:6: error: type mismatch;&lt;br /&gt;
   found   : Int(123)&lt;br /&gt;
   required: java.lang.String&lt;br /&gt;
         str=123&lt;br /&gt;
&lt;br /&gt;
===== Mixed paradigm =====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object oriented and functional programming. How can this happen? Functional world advocates immutability but object oriented world is all about state and how do you mutate it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . Roughly translating the above line to Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as below&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks so much simpler and less verbose. Even though the above example shows immutable collection example, scala also provides mutable collection and object types under the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As it can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So its the best of both worlds. Another part of functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
===== Sophisticated Syntax/Features =====&lt;br /&gt;
Sophisticated syntax and features are present in other functional languages like Haskell, (O)Caml and Erlang. Consider the following example,&lt;br /&gt;
&lt;br /&gt;
   val name = &amp;quot;Jackie Chan&amp;quot;&lt;br /&gt;
   println(name.getClass) //prints out String.&lt;br /&gt;
&lt;br /&gt;
Previously we saw that [http://www.scala-lang.org/ Scala] is a statically typed language and yet in the above example we don't specify what type &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; is. In Java, you would type in the following:&lt;br /&gt;
&lt;br /&gt;
 String name = &amp;quot;Jackie Chan&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In Java you specify what type the name variable is, but the [http://www.scala-lang.org/ scala] compiler can automatically detect the type of the variable even if you don't specify it. Consider the following example,&lt;br /&gt;
&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
 val persons = List(&lt;br /&gt;
                        Person(&amp;quot;Jackie Chan&amp;quot;, 51), Person(&amp;quot;Jet Li&amp;quot;, 41),&lt;br /&gt;
                        Person(&amp;quot;RajniKanth&amp;quot;, 51), Person(&amp;quot;Kamal Hasan&amp;quot;, 44),&lt;br /&gt;
                        Person(&amp;quot;Martin Odersky&amp;quot;, 18), Person(&amp;quot;Steve Yegge&amp;quot;, 23))&lt;br /&gt;
 //notice that you don't have to use 'new' keyword to create new instances. This is taken care of by the companion objects.&lt;br /&gt;
&lt;br /&gt;
The above lines of code create a list with 6 different persons(An immutable list)&lt;br /&gt;
&lt;br /&gt;
Now, just like ruby, scala supports the concepts of [http://en.wikipedia.org/wiki/Closure_(computer_science) closure]. Let's see what it is.&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( { p: Person =&amp;gt; p.age == 3})&lt;br /&gt;
&lt;br /&gt;
In the above set of lines, the code within the '{ }' brackets is a function's body. The compiler created a function which takes a single argument and returns either true or false. &lt;br /&gt;
&lt;br /&gt;
===== A Scalable Language =====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. This feature is often called as [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching] because you are splitting open the class and adding/overriding methods (in)|(to) the class. Often this leads to unexpected behavior at runtime because, other libraries including into build path may depend on some methods which you changed. Scala provides yet another feature called implicits.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
Ruby is a dynamically typed Object Oriented Language which supports multiple programming paradigms, including functional, object-oriented, imperative and reflective. In Ruby, everything is an object, every bit of information and code can have its own properties and actions. However, Ruby’s blocks can be functional. A Ruby programmer can attach a closure to any method, which generates a functional block inside an object oriented code. A closure is a piece of code that can access the lexical environment of its definition [http://www.ruby-lang.org/en/ 11].&lt;br /&gt;
&lt;br /&gt;
Consider the following code snippet in Ruby which uses Object Oriented concepts like Classes and functional programming concepts like lambda.&lt;br /&gt;
&lt;br /&gt;
 class Multiply&lt;br /&gt;
   def initialize(n)&lt;br /&gt;
     @block = lambda {|a| n * a}&lt;br /&gt;
   end&lt;br /&gt;
   def mul(a)&lt;br /&gt;
     @block.call a&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 twoMultiplier = Multiply.new 2                     &lt;br /&gt;
 puts twoMultiplier.mul(6)&lt;br /&gt;
&lt;br /&gt;
Here,'''''@block''''' is a closure. When we call the class ''Multiply'' using '''''twoAdder = Multiply.new 2''''' ,the ''initialize'' method is called by passing the parameter 2. Here n=2 binds itself to the block. So @block will be 2*a, that is,the closure remembers the parameter with which the initialize method was called even after the initialize method exits.  &lt;br /&gt;
&lt;br /&gt;
This value is used when the block is called in the add method.  &lt;br /&gt;
Thus,'''''twoMultiplier.mul(6)''''' will return 2*6 = 12&lt;br /&gt;
&lt;br /&gt;
Blocks are basically nameless functions which can be passed to a function and then that function can invoke the passed in nameless function. This is a common style called [http://en.wikipedia.org/wiki/Higher-order_function higher order functions] among languages that handle functions as first class objects. Basically blocks can be designed for loop abstraction and lets the user to design their own way of iterating the values, thereby hiding the implementation details. &lt;br /&gt;
For example, if we want to iterate backwards from the end to the beginning without revealing its internal implementations, we could implement the loop logic inside the block and pass it to a method or function.&lt;br /&gt;
&lt;br /&gt;
Here is a [http://www.ruby-lang.org/en/ Ruby] implementation of block:&lt;br /&gt;
 &lt;br /&gt;
 def printlist(array,&amp;amp;reverse)&lt;br /&gt;
    array.each do |element|&lt;br /&gt;
       puts &amp;quot;array element: #{element}&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
    reverse.call(array)   /* Here it prints the reverse implementation of list*/&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
 printlist([1,2,3,4,5,6]) { |array| &lt;br /&gt;
   array.reverse.each do |element| &lt;br /&gt;
     puts &amp;quot;array element: #{element}&amp;quot; &lt;br /&gt;
   end &lt;br /&gt;
 }&lt;br /&gt;
The statements between { } is a block and it gets called by &amp;lt;code&amp;gt;reverse.call(array)&amp;lt;/code&amp;gt;within the printlist method.&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63018</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=63018"/>
		<updated>2012-09-09T01:22:07Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Scala */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and data is immutable****. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily.&lt;br /&gt;
 &lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
=== Lambda ===&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
= Scala =&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. [http://www.scala-lang.org/ Scala] was conceived in 2001 and implemented by Martin Odersky.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
==== Statically Typed ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] belongs to the family of languages which encode the type information of each and every variable in the generated code. The compiler makes sure you are not doing something incorrectly. For example, lets consider the following example of code where the type is not encoded,&lt;br /&gt;
&lt;br /&gt;
In [http://www.ruby-lang.org/en/ Ruby],&lt;br /&gt;
   irb(main):001:0&amp;gt; str=&amp;quot;Hello World&amp;quot;&lt;br /&gt;
    =&amp;gt; &amp;quot;Hello World&amp;quot;&lt;br /&gt;
    irb(main):002:0&amp;gt; puts str.class&lt;br /&gt;
    String&lt;br /&gt;
    irb(main):003:0&amp;gt; str=123&lt;br /&gt;
    =&amp;gt; 123&lt;br /&gt;
    irb(main):004:0&amp;gt; puts str.class&lt;br /&gt;
    Fixnum&lt;br /&gt;
&lt;br /&gt;
In the above example, first we define 'str' variable to be of type String and then as a number. So basically, no type information is associated with the variable at any point in the program. Hence we can easily reassociate that variable with an object/instance&lt;br /&gt;
of a different type. This is a feature of all dynamically typed languages(like Ruby, Python, Clojure). However most of the statically typed languages such as Scala, Java, C/C++ do not allow you do so. In [http://www.scala-lang.org/ Scala],&lt;br /&gt;
&lt;br /&gt;
  scala&amp;gt; var str=&amp;quot;Hello World&amp;quot;&lt;br /&gt;
  str: java.lang.String = Hello World&lt;br /&gt;
  scala&amp;gt; str=123&lt;br /&gt;
  &amp;lt;console&amp;gt;:6: error: type mismatch;&lt;br /&gt;
   found   : Int(123)&lt;br /&gt;
   required: java.lang.String&lt;br /&gt;
         str=123&lt;br /&gt;
&lt;br /&gt;
==== Mixed paradigm ====&lt;br /&gt;
[http://www.scala-lang.org/ Scala] is a strange specimen. It is a complete blend of object oriented and functional programming. How can this happen? Functional world advocates immutability but object oriented world is all about state and how do you mutate it to fit your needs. [http://www.scala-lang.org/ Scala] allows you create both mutable and immutable objects. Consider the following example,&lt;br /&gt;
 val str: String = &amp;quot;Hello World&amp;quot;&lt;br /&gt;
In the first line, an immutable version(a misnomer indeed) of &amp;lt;code&amp;gt;str&amp;lt;/code&amp;gt; is being created . Roughly translating the above line to Java is below:&lt;br /&gt;
&lt;br /&gt;
 final String str = &amp;quot;Hello World&amp;quot;; //note the extra semi-colon&lt;br /&gt;
Consider the next example below,&lt;br /&gt;
 val list: List[String] = List(&amp;quot;Scala&amp;quot;, &amp;quot;is&amp;quot;, &amp;quot;the coolest&amp;quot;, &amp;quot;language&amp;quot;, &amp;quot;in the world!&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
The same code can be written in Java as below&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;String&amp;gt; mutableList = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  list.add(&amp;quot;Scala&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;is&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;the coolest&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;language&amp;quot;);&lt;br /&gt;
  list.add(&amp;quot;in the world!&amp;quot;);&lt;br /&gt;
  List&amp;lt;String&amp;gt; immutableList = Collections.immutableList(mutableList);&lt;br /&gt;
&lt;br /&gt;
Compared to Java, [http://www.scala-lang.org/ Scala] reduces the total number of lines you need to type and at the same time looks so much simpler and less verbose. Even though the above example shows immutable collection example, scala also provides mutable collection and object types under the package &amp;lt;code&amp;gt;scala.collection.mutable.*&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As it can be observed, even though [http://www.scala-lang.org/ Scala] advocates immutability, it does not restrict you from creating mutable objects. So its the best of both worlds. Another part of functional world is the concept of functions as ''''first class members'''' of the language. Some of the common languages like Ruby, Python and JavaScript all incorporate this feature. In the sense you can pass around functions to methods as a parameter. Enough talking;&lt;br /&gt;
&lt;br /&gt;
Let us have a class say &amp;lt;code&amp;gt;'Person'&amp;lt;/code&amp;gt; which has properties, &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and another variable &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;.&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;br /&gt;
 class Person{&lt;br /&gt;
    private String name;&lt;br /&gt;
    private int age;&lt;br /&gt;
    public String getName(){&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
    public void setName(String s){&lt;br /&gt;
        this.name = s;&lt;br /&gt;
    }&lt;br /&gt;
    public int getAge(){&lt;br /&gt;
        return age;&lt;br /&gt;
    }&lt;br /&gt;
    public void setAge(int age){&lt;br /&gt;
        this.age = age;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
&lt;br /&gt;
This single line is equivalent to the above java code! Getters for &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;age&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;equals()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;hashCode()&amp;lt;/code&amp;gt; method are automatically generated for you by the compiler. Isn't this an awesome feature? &lt;br /&gt;
&lt;br /&gt;
Now assume we have a list of persons and we want to filter out all the persons who are of age 23. How would you do that in Java?&lt;br /&gt;
&lt;br /&gt;
  List&amp;lt;Person&amp;gt; persons; //has a bunch of person objects in it.&lt;br /&gt;
  List&amp;lt;Person&amp;gt; twentyThree = new ArrayList&amp;lt;Person&amp;gt;();&lt;br /&gt;
  for(Person p: persons){&lt;br /&gt;
      if(p.getAge() == 23){&lt;br /&gt;
          twentyThree.add(p);&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In [http://www.scala-lang.org/ Scala]:&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( _.age == 23)&lt;br /&gt;
&lt;br /&gt;
That's it! In case you are wondering whats going on, filter is a method present on scala.List class and the code block  &amp;lt;code&amp;gt;_.age == 23&amp;lt;/code&amp;gt; is a function created on the fly and passed onto the filter method. More precisely its called a [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] - a functional concept which can be emulated in java only using anonymous inner classes. Scala's compiler transforms our one line function into some anonymous inner classes when generating java byte code, allowing developers to define functions in a simple manner.&lt;br /&gt;
&lt;br /&gt;
In fact, every function is an object in [http://www.scala-lang.org/ Scala]. Scala's standard library has a number of functions which are objects themselves.&lt;br /&gt;
&lt;br /&gt;
==== Sophisticated Syntax/Features ====&lt;br /&gt;
Sophisticated syntax and features are present in other functional languages like Haskell, (O)Caml and Erlang. Consider the following example,&lt;br /&gt;
&lt;br /&gt;
   val name = &amp;quot;Jackie Chan&amp;quot;&lt;br /&gt;
   println(name.getClass) //prints out String.&lt;br /&gt;
&lt;br /&gt;
Previously we saw that [http://www.scala-lang.org/ Scala] is a statically typed language and yet in the above example we don't specify what type &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; is. In Java, you would type in the following:&lt;br /&gt;
&lt;br /&gt;
 String name = &amp;quot;Jackie Chan&amp;quot;&lt;br /&gt;
&lt;br /&gt;
In Java you specify what type the name variable is, but the [http://www.scala-lang.org/ scala] compiler can automatically detect the type of the variable even if you don't specify it. Consider the following example,&lt;br /&gt;
&lt;br /&gt;
 case class Person(name: String, age: Int)&lt;br /&gt;
 val persons = List(&lt;br /&gt;
                        Person(&amp;quot;Jackie Chan&amp;quot;, 51), Person(&amp;quot;Jet Li&amp;quot;, 41),&lt;br /&gt;
                        Person(&amp;quot;RajniKanth&amp;quot;, 51), Person(&amp;quot;Kamal Hasan&amp;quot;, 44),&lt;br /&gt;
                        Person(&amp;quot;Martin Odersky&amp;quot;, 18), Person(&amp;quot;Steve Yegge&amp;quot;, 23))&lt;br /&gt;
 //notice that you don't have to use 'new' keyword to create new instances. This is taken care of by the companion objects.&lt;br /&gt;
&lt;br /&gt;
The above lines of code create a list with 6 different persons(An immutable list)&lt;br /&gt;
&lt;br /&gt;
Now, just like ruby, scala supports the concepts of [http://en.wikipedia.org/wiki/Closure_(computer_science) closure]. Let's see what it is.&lt;br /&gt;
&lt;br /&gt;
 val twentyThree: List[Person] = persons.filter( { p: Person =&amp;gt; p.age == 3})&lt;br /&gt;
&lt;br /&gt;
In the above set of lines, the code within the '{ }' brackets is a function's body. The compiler created a function which takes a single argument and returns either true or false. &lt;br /&gt;
&lt;br /&gt;
==== A Scalable Language ====&lt;br /&gt;
In almost all programming languages, there is a necessity to profile the running time of the procedures and tune its performance. The old way of doing things in Java would be:&lt;br /&gt;
&lt;br /&gt;
 public class Main{&lt;br /&gt;
 public static int factorial(int x){&lt;br /&gt;
   if(x == 0 || x == 1) return 1&lt;br /&gt;
   else return x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  public static void main(String [] args){&lt;br /&gt;
    long beforeTime = System.currentTimeMillis();&lt;br /&gt;
    int result = factorial(5);&lt;br /&gt;
    System.out.println(&amp;quot;Total time taken to execute factorial(5) is &amp;quot; + (System.currentTimeMillis() - result)+&amp;quot;ms&amp;quot;);&lt;br /&gt;
    System.out.println(&amp;quot;factorial(5) = &amp;quot; + result);&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
However, if you want to find out the execution time of some other method, you would have to type in all the above lines again. So much for code re-use or [http://en.wikipedia.org/wiki/DRY DRY (dont't repeat yourself)]! Lets see how its done in [http://www.scala-lang.org/ Scala].&lt;br /&gt;
&lt;br /&gt;
 object Main{&lt;br /&gt;
  def main(args: Array[String]){&lt;br /&gt;
    def factorial(x: Int):Int = x match{&lt;br /&gt;
      case 0 | 1 =&amp;gt; 1&lt;br /&gt;
      case _ =&amp;gt; x * factorial(x-1)&lt;br /&gt;
  }&lt;br /&gt;
  import System.currentTimeMillis&lt;br /&gt;
  def timeIt(msg: String = &amp;quot;Time to execute is: &amp;quot;)(func: =&amp;gt; Unit){&lt;br /&gt;
    val before = currentTimeMillis&lt;br /&gt;
    func&lt;br /&gt;
    println(msg + (currentTimeMillis - before) + &amp;quot;ms&amp;quot;)&lt;br /&gt;
  }&lt;br /&gt;
  timeIt(&amp;quot;Total time taken to execute factorial(5) is &amp;quot;){&lt;br /&gt;
      val result = factorial(5)&lt;br /&gt;
      println(&amp;quot;factorial(5) = &amp;quot; + result)&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
 //would print: factorial(5) = 120&lt;br /&gt;
 // Total time taken to execute factorial(5) is 1ms&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
That's not right! The function &amp;lt;code&amp;gt;timeIt&amp;lt;/code&amp;gt; looks like a feature built into the language. Try saving the above code into a separate file and run it - It will still work. Using this feature, it is possible to build powerful DSL languages which can run at full speed on JVM.&lt;br /&gt;
&lt;br /&gt;
Ruby allows you to add new methods to objects. This feature is often called as [http://en.wikipedia.org/wiki/Monkey_patch Monkey Patching] because you are splitting open the class and adding/overriding methods (in)|(to) the class. Often this leads to unexpected behavior at runtime because, other libraries including into build path may depend on some methods which you changed. Scala provides yet another feature called implicits.&lt;br /&gt;
&lt;br /&gt;
In Java, &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt; class is &amp;lt;code&amp;gt;final&amp;lt;/code&amp;gt; so there is no way you can add new methods to it. But with implicits you can do more! Suppose you have some text in memory and you know it represents a number. But in Java the usual way to convert string to int is to do a &amp;lt;code&amp;gt;Integer.parseInt(string)&amp;lt;/code&amp;gt; which seems so unnecessary. Let us make our lives easier...&lt;br /&gt;
&lt;br /&gt;
  implicit def strToInt(str: String) = new {&lt;br /&gt;
    def asInt = Integer.parseInt(str)&lt;br /&gt;
  }&lt;br /&gt;
  val str = &amp;quot;1234&amp;quot;&lt;br /&gt;
  println(str.asInt * 3) //prints out 3702&lt;br /&gt;
&lt;br /&gt;
The above code gives us an impression as if String class has gained new &amp;lt;code&amp;gt;asInt&amp;lt;/code&amp;gt; method. Can static object oriented languages do this? No! Infact scala cheats by calling our implicits to convert it into a different object as and when needed.&lt;br /&gt;
&lt;br /&gt;
The above functionalities are purely object oriented, yet they are safe. They don't pollute the global namespace, unlike Ruby or Python.&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=62997</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=62997"/>
		<updated>2012-09-08T21:46:09Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and data is immutable****. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily.&lt;br /&gt;
 &lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
=== Lambda ===&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=62960</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=62960"/>
		<updated>2012-09-08T18:24:36Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Functional Programming */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and data is immutable (i.e. functional programming uses [http://en.wikipedia.org/wiki/Persistent_data_structure persistent data structures]). Everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [2,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily.&lt;br /&gt;
 &lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
=== Lambda ===&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=62959</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=62959"/>
		<updated>2012-09-08T18:23:55Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* Functional Programming */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and data is immutable (i.e. functional programming uses [http://en.wikipedia.org/wiki/Persistent_data_structure persistent data structures]). Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [2,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily.&lt;br /&gt;
 &lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
=== Lambda ===&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=62957</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=62957"/>
		<updated>2012-09-08T17:50:23Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: Added Functional Programming Section&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
Functional programming treats computation as the evaluation of mathematical functions. It is compute-centric rather than data-centric. Functional programming keeps no global state, does not use for or while loops, and data is immutable****. Instead, everything is done using functions, usually functions that evaluate mathematical expressions. Each of these functions maintain no internal state and will always produce the same output given the same input. &lt;br /&gt;
&lt;br /&gt;
Let's look at an example. Suppose we have a list of numbers and we want to multiply each number in the list by 2. The first approach is the imperitive style:&lt;br /&gt;
&lt;br /&gt;
     array[] = {1,2,3,4,5}&lt;br /&gt;
    for(i=0 ; i&amp;lt;array.length; i++){&lt;br /&gt;
       array[i] = array[i] * 2;&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
In the above example, array[] is a global variable. If we fail to check the array length, then a runtime exception occurs which might result in the program being crashed. As far as functional style, there is a function called map(func,seq)(in python language) where the function 'func' is applied to each member of seq. The following code is written in a functional style.&lt;br /&gt;
&lt;br /&gt;
      numbers = [1,2,3,4,5]&lt;br /&gt;
     /*  define a method called compute on each number in the list */&lt;br /&gt;
     def compute(var):&lt;br /&gt;
         var = var * 2&lt;br /&gt;
         return var&lt;br /&gt;
     /* Now call the map function */&lt;br /&gt;
     L = map(compute,numbers)&lt;br /&gt;
     print L                   // L will print [1,4,6,8,10]&lt;br /&gt;
 &lt;br /&gt;
Notice that there is no global data nor any nested loops and the bound checking is handled internally within the map function. The programmer is relieved of of runtime errors and thus can debug the program easily.&lt;br /&gt;
 &lt;br /&gt;
Some advantages of this approach are:&lt;br /&gt;
* Easier debugging: Since every thing is broken down into small simple functions, the functions are often easy to debug.&lt;br /&gt;
* More compact code: Functional programming typically requires fewer lines of code. Since compution is done by function code reuse is prevelent.&lt;br /&gt;
* Nothing depends on state: Because functional programs keep no state information, the functions will always operate the same regardless of the past history of the program.&lt;br /&gt;
&lt;br /&gt;
= Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
=== Lambda ===&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=62913</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=62913"/>
		<updated>2012-09-07T20:15:33Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
= Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
Motivation for Mixing&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
=== Lambda ===&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=62908</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=62908"/>
		<updated>2012-09-07T19:55:19Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: Added organization to top of page&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
= Functional Programming =&lt;br /&gt;
&lt;br /&gt;
= Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional and Object-Oriented Programming =&lt;br /&gt;
&lt;br /&gt;
== Motivation for Mixing ==&lt;br /&gt;
&lt;br /&gt;
== Functional Techniques useful for Object-Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
=== Lambda ===&lt;br /&gt;
&lt;br /&gt;
=== Currying ===&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
== Examples of Mixing ==&lt;br /&gt;
&lt;br /&gt;
=== Scala ===&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
&lt;br /&gt;
=== Clojure ===&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Mixing Functional &amp;amp; O-O code = &lt;br /&gt;
&lt;br /&gt;
This chapter deals with the mixing of functional and object-oriented programming paradigms. We start with listing the different programming paradigms available today. We introduce functional and object-oriented approaches briefly and then discuss the advantages of one over the other. Following this, we discuss some aspects and features of mixing both the approaches. Finally, we talk about few languages that constitute such a mix.&lt;br /&gt;
&lt;br /&gt;
== Programming Paradigms Today==&lt;br /&gt;
&lt;br /&gt;
Several programmatic approaches to solve a particular task lead to distinct programming paradigms like, &amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Imperative_programming Imperative Programming] &amp;lt;br&amp;gt;&lt;br /&gt;
* Functional programming&amp;lt;br&amp;gt;&lt;br /&gt;
* Object Oriented programming&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Logic_programming Logical programming], etc.  &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
Lets focus on functional and object oriented programming approaches.&lt;br /&gt;
&lt;br /&gt;
== Functional Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_programming Functional programming] is the task of decomposing a problem into a number of functions. Selectively executing these functions results in the solution to the problem. The functions mostly behave as mathematical. For given set of inputs the program should always return the same output. It usually concentrates on what type of problem we are dealing with rather than on the details of how to solve the problem. For example lets say there is a function which calculates area of a square. If we use it six times then we end up with area of a cube. Thus functional programming helps to build complex systems.&lt;br /&gt;
&lt;br /&gt;
=== Approach ===&lt;br /&gt;
&lt;br /&gt;
Expressions are the collection of variables and operations resulting in a single value this also deals with the way of solving the problem as expressions. Hence also called Expression related programming. It is structured as expression where each expression can be encapsulated in another yielding the result. Making the change in data structures as the program runs is called [http://en.wikipedia.org/wiki/Side_effect_(computer_science) side effects]. Purely functional language has no side effects. Language like Haskell is a pure functional language . Some languages need many approaches for achieving the desired result. Such languages are multi-paradigm. Examples for such languages are C++, Python,Lisp. Its like evaluating an expression and use the resulting value for something.&lt;br /&gt;
&lt;br /&gt;
Structure of functional programming :&lt;br /&gt;
&lt;br /&gt;
  (fn2 ( fn1 ()[input list] ) [])  =&amp;gt; fn1 takes input list and the output of fn1 is used as input to fn2. Its a schematic representation of  &lt;br /&gt;
                                      how functional programming works.&lt;br /&gt;
&lt;br /&gt;
Functional programming feature (Python) :&lt;br /&gt;
&lt;br /&gt;
  m = map(lambda i : i*i , numbers)&lt;br /&gt;
where ''numbers'' is an array of numbers and ''lambda'' is [http://en.wikipedia.org/wiki/Closure_%28computer_science%29 closure]. &lt;br /&gt;
&lt;br /&gt;
Python has some functions like map, filter, reduce to support functional programming style. In the example above, the 'map' is a high-order function that takes a function and an array of numbers as input. The ''lambda'' takes i as input and returns i*i as output. Every result returned is appended to a list and produced as output. In functional programming, the programmer is given a natural framework for developing smaller, simpler, and more general modules, which are then glued together.&lt;br /&gt;
&lt;br /&gt;
== Object Oriented Programming ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming Object-oriented programming] is a programming technique where everything is defined as an object. Objects are well-defined discrete bundles of data(attributes) and the associated functions(behavior). They are devised to resemble real-life objects and are uniquely identifiable by a name. The attributes could be of simple datatype(int, String, Boolean) or objects themselves. The behavior is defined by methods to use and manipulate the attributes. The values of attributes of an object at an instant is the state of the object. OO Programming allows objects to have their state retained throughout the code until manipulated otherwise. Objects are capable of housekeeping their own states, interacting and establishing relationships with other objects, inheriting, etc.&lt;br /&gt;
&lt;br /&gt;
=== Fundamental concepts ===&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Class_%28computer_science%29 class] is a user-defined datatype that provides implementation details to define the attributes and their properties. It is an abstract representation of an object(i.e.,) like a mold for objects.&lt;br /&gt;
An instance is an executable copy of a class. They are the actual objects created using the ‘class mold’ on run time.&lt;br /&gt;
Methods are a set of procedural statements or functions to define the behavior of an object, convey the current state, modify values of the attributes, etc.&lt;br /&gt;
&lt;br /&gt;
Example :&lt;br /&gt;
&lt;br /&gt;
An object in Java might look like this:&lt;br /&gt;
&lt;br /&gt;
public class Person {&lt;br /&gt;
  private String name;&lt;br /&gt;
  public Person() {&lt;br /&gt;
  }&lt;br /&gt;
  public void setName(String name) {&lt;br /&gt;
      this.name = name;&lt;br /&gt;
  }&lt;br /&gt;
  public String getName() {&lt;br /&gt;
      return this.name;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, OO Programming allows the programmer to set the ''name'' attribute of the class ''Person'' and get the name whenever needed in the code. An object of this class Person will remain in memory forever as long as there is a reference to it. As OO Programming allows objects to have their state retained, the value of the ''name'' attribute for a particular ''Person'' object remains the same across any part of the code until it is set differently.&lt;br /&gt;
&lt;br /&gt;
=== Features ===&lt;br /&gt;
&lt;br /&gt;
Three primary characteristics of object oriented programming are Encapsulation, Polymorphism, and Inheritance.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29 Encapsulation] is the ability of objects to hide visibility of their attributes and behavior, thereby providing service independent of implementation.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming Polymorphism] allows identical operations to behave differently in different contexts. The operations that can be performed on an object make up its interface. They enable addressing of operations with the same name in different objects.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29 Inheritance] is one where an existing type can be used to derive a new type. Derived types inherit the data and operations of the super-type. And also, they can overwrite existing operations or add new ones.&lt;br /&gt;
&lt;br /&gt;
There are other important features of O-O programming like [http://en.wikipedia.org/wiki/Message_passing message passing], [http://en.wikipedia.org/wiki/Abstraction abstraction], delegation, etc. &lt;br /&gt;
&lt;br /&gt;
Now, we have seen both the approaches and their features in brief. Lets discuss the advantages of one over the other.&lt;br /&gt;
&lt;br /&gt;
== Advantages == &lt;br /&gt;
&lt;br /&gt;
=== Functional Approach over OO Approach[[http://www.jot.fm/issues/issue_2009_09/article5.pdf 8]]===&lt;br /&gt;
* Functional programming solves the problem with lesser number of lines of code than the OO programming style.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no side effect as they use immutable data structures also called [http://en.wikipedia.org/wiki/Persistent_data_structure Persistent Data Structure] which will have no change in the state of variables. Hence program dont have to depend on history.&amp;lt;br&amp;gt;&lt;br /&gt;
* There is no limit in the numeric types used as opposed to OO languages which mainly depend on primitive data types.&amp;lt;br&amp;gt;&lt;br /&gt;
* A programmer is given the freedom to think in terms of what to solve in the problem rather than concentrating on how to solve and the flow of the program.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for calculation intensive programs.&lt;br /&gt;
&lt;br /&gt;
=== OO Approach over Functional Approach===&lt;br /&gt;
* Everything can be represented in an object and it has the attributes associated with it and hence the state of the object is known at any time.&amp;lt;br&amp;gt;&lt;br /&gt;
* A complex system can be subdivided into modules of objects where as in functional approach, many functions inter operate to form a complex system.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Reusability Re-usability] (i.e.) OO approach enables programmers to create new objects that inherits many of its features from existing objects. This makes object-oriented programs easier to modify than functional.&amp;lt;br&amp;gt;&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Debug Debugging] in Object Oriented environment is easy compared with functional approach where a small error in one function causes the whole system (i.e. all the functions) to fail.&amp;lt;br&amp;gt;&lt;br /&gt;
* Suitable for making application-oriented software. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both the approaches have their advantages and disadvantages. What if we could get the best of both the worlds? The next section deals with the aspects and features of how well both the approaches are mixed together in some languages.&lt;br /&gt;
&lt;br /&gt;
== Mixing Functional &amp;amp; OO Code - Best of both the worlds == &lt;br /&gt;
&lt;br /&gt;
Languages that are a mix of functional and object oriented approaches(eg. Scala[[http://www.scala-lang.org/node/1305 1]], Clojure[[http://oreilly.com/catalog/9781934356333 10]], etc.) make use of best of both the worlds. They support various aspects of functional and object oriented approaches. They have a bunch of functional approach features[[http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf 6]], which object oriented programming languages(like Java) lack which includes closures. Closures are first-class functions with free variables that are bound in the lexical environment. These languages also sport a very malleable syntax that makes them well suited for &amp;quot;domain specific languages&amp;quot; with the benefits of static typing. They are more expressive, extensible and allow reuse of programming abstractions.&lt;br /&gt;
&lt;br /&gt;
Certain languages like Scala, Clojure, etc run on Java Virtual Machine(JVM) ensuring portability to all underlying platforms. They even support immutable objects. In Scala, new language constructs can be added in the form of libraries. They allow safe reuse[[http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf 9]] of programming abstractions and type-safe extension of software.&lt;br /&gt;
&lt;br /&gt;
===Lambda===&lt;br /&gt;
&lt;br /&gt;
A lambda[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] expression is an anonymous function that contain expressions and statements, and can be used to create delegates or expression  types. Such kind of anonymous function can be defined and passed around as easily as other data types and can be used to contain functionality that need not be named. Some notable examples include closures[[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5]] and currying. Lambda functions with no name can be called using the variable assigned to it. &lt;br /&gt;
&lt;br /&gt;
  g = lambda x: x*2  &lt;br /&gt;
  g(3)=6&lt;br /&gt;
&lt;br /&gt;
We can have lambda function without assigning it to a variable which can be used as inline-function.&lt;br /&gt;
&lt;br /&gt;
  (lambda x: x*2)(3)&lt;br /&gt;
&lt;br /&gt;
In [http://en.wikipedia.org/wiki/Clojure Clojure] as a functional language, the creation of a chunk of behavior that can be assigned to a variable (known as a lambda) is trivial. Below are two ways to create a lambda that returns the square of its argument.&lt;br /&gt;
&lt;br /&gt;
  (def square1 (fn [n] (* n n)))&lt;br /&gt;
  (def square2 #(* % %))&lt;br /&gt;
&lt;br /&gt;
===Currying ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Currying Currying] transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. It reuses a partially applied function where the function is originally defined as accepting n parameters.It can be interpreted as the technique to decompose a function that takes n parameters into n function each of them taking 1 parameter. For example to say in algebraic terms,consider the function f which takes 3 parameters x,y,z and Currying means that we can rewrite the function as a composition of 3 functions:&lt;br /&gt;
&lt;br /&gt;
  f(x,y,z) = 4*x+3*y+2*z&lt;br /&gt;
  f(x)(y)(z) = 2*z+(3*y+(4*x))&lt;br /&gt;
&lt;br /&gt;
In Scala, currying takes advantage of Scala’s syntactic sugar. Below is a currying example in Scala. This function creates a multiplier function which takes two arguments and partially defines it by assigning a constant to one argument and assigning it to a variable .Later the function is called by assigning the second argument.&lt;br /&gt;
&lt;br /&gt;
  def multiplier(i: Int)(factor: Int) = i * factor =&amp;gt; method named multiplier which takes two parameters is defined &lt;br /&gt;
  val byFive = multiplier(5) _                     =&amp;gt; The method is redefined with accepting one parameter and store it in a variable.&lt;br /&gt;
  val byTen = multiplier(10) _&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byFive(2)                                 =&amp;gt; Method called by giving the second parameter.&lt;br /&gt;
  res4: Int = 10&lt;br /&gt;
  &lt;br /&gt;
  scala&amp;gt; byTen(2)&lt;br /&gt;
  res5: Int = 20&lt;br /&gt;
&lt;br /&gt;
===Less Verbosity===&lt;br /&gt;
&lt;br /&gt;
In Java each variable should have its type defined beforehand. Whereas in languages like Scala, it is more concise and easier to read than the equivalent Java.&lt;br /&gt;
&lt;br /&gt;
For example,  a Map can be created with a simple syntax in Scala,Clojure than in Java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;table&amp;gt;&lt;br /&gt;
&amp;lt;tr&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Java'''&lt;br /&gt;
 Map&amp;lt;String, Integer&amp;gt; nMap = new HashMap&amp;lt;String, Integer&amp;gt;();&lt;br /&gt;
 nMap.put(&amp;quot;one&amp;quot;, 1);&lt;br /&gt;
 nMap.put(&amp;quot;two&amp;quot;, 2);&lt;br /&gt;
 nMap.put(&amp;quot;three&amp;quot;, 3);&lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Scala'''&lt;br /&gt;
  &lt;br /&gt;
 var nMap = Map(&amp;quot;one&amp;quot; -&amp;gt; 1, &amp;quot;two&amp;quot; -&amp;gt; 2, &amp;quot;three&amp;quot; -&amp;gt; 3)&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;td&amp;gt;&lt;br /&gt;
'''Clojure'''&lt;br /&gt;
 &lt;br /&gt;
 (doto (new Java.util.HashMap)(.put “a” 1)(.put “b” 2))&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
  &lt;br /&gt;
&amp;lt;/td&amp;gt;&lt;br /&gt;
&amp;lt;/tr&amp;gt;&lt;br /&gt;
&amp;lt;/table&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, Scala compiler knows that nMap uses Strings as keys, and Integers as values. Unlike Java, this need not be specified beforehand. Scala could figure it out itself. Moreover, Scala will give an error if a different key-value pair is tried to insert. This is called &amp;quot;type inference&amp;quot;. This prevents a whole class of bugs at run time just like Java but with less verbosity.&lt;br /&gt;
In a similar way Clojure also involves only few lines of code compared with the object oriented Java language which takes many lines of code.A simple Clojure example and the associated Java code :&lt;br /&gt;
Example&lt;br /&gt;
&lt;br /&gt;
   (defn blank? [s] (every? #(Character/isWhitespace %) s))&lt;br /&gt;
&lt;br /&gt;
The innermost function Character/isWhiteSpace checks the first argument % for any whitespace and returns true if it is. every? invoke the above inner function for all elements in the collection s.It has no variables, no branches etc.&lt;br /&gt;
&lt;br /&gt;
Java code&lt;br /&gt;
isBlank() method checks to see whether a string is blank or contains only whitespace.&lt;br /&gt;
&lt;br /&gt;
  public class Stringcheck{&lt;br /&gt;
     public static boolean isBlank(String str){&lt;br /&gt;
           int len;&lt;br /&gt;
           if(str==null || (strlen =str.length())==0)&lt;br /&gt;
              return true;&lt;br /&gt;
           for(int i=0; i&amp;lt;strlen;i++) {&lt;br /&gt;
                 if((Character.isWhitespace(str.charAt(i))==false)){&lt;br /&gt;
                        return false;&lt;br /&gt;
                    }&lt;br /&gt;
             }&lt;br /&gt;
         return true;&lt;br /&gt;
      }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=== Pattern Matching ===&lt;br /&gt;
&lt;br /&gt;
To say simply, a [http://en.wikipedia.org/wiki/Pattern_matching Pattern matching] is a technique to search string for the occurrence of any patterns or regularity. Pattern matching is an elegant way to decompose objects into their constituent parts for processing.Many languages support the concept of pattern matching. Perl supports pattern matching using the pattern definition mini language called regular expressions, also called regexes  or  REs, which is borrowed from the regular expressions used in many Unix tools, such as  grep()  and  sed().The risk that the parts of an object might be changed outside of the control of the enclosing object is avoided. For example, if there is a Person class that contains a list of addresses, it will not be an issue to expose that list to clients if the list is immutable. The users will not be able to change the list  unexpectedly.Given below is a simple example for pattern matching used in Perl: &lt;br /&gt;
&lt;br /&gt;
 $mystring = &amp;quot;Hello world!&amp;quot;;  // Perls way of assigning string to a variable.&lt;br /&gt;
 if($mystring =~ m/World/) { print &amp;quot;Yes&amp;quot;; } // Checks the string stored in variable mystring has the string &amp;quot;World&amp;quot;.&lt;br /&gt;
 $mystring =~ s/world/mom/; // Replaces the string &amp;quot;world&amp;quot; stored in mystring to mom.&lt;br /&gt;
&lt;br /&gt;
Another sample of regular expression in java :&lt;br /&gt;
&lt;br /&gt;
 String mystring=&amp;quot;Hello World&amp;quot; ; &lt;br /&gt;
 Pattern str = Pattern.compile(&amp;quot;\\w+&amp;quot;);  =&amp;gt; Pattern stored for matching.&lt;br /&gt;
 Matcher fit = str.matcher(mystring);    =&amp;gt; Matcher class which perform matching of the string with the pattern defined.&lt;br /&gt;
 if(fit.matches())&lt;br /&gt;
&lt;br /&gt;
As languages like Scala and Clojure support procedural code, pattern matching is done as equal or with less difficulty compared with Java which needs to use regex. Scala can even be embedded into XML as its syntax is somewhat similar.Given below an overview of how regular expression is achieved in Clojure.&lt;br /&gt;
Data are manipulated in Clojure through the sequence called seq which is a logical list. Clojure can access java collections, its collections, Regular expression matches via the seq also called seq-able. Clojure's regular expression uses java.util.regex library at the lowest level. For achieving that the keyword re-seq is used. &lt;br /&gt;
 Syntax:&lt;br /&gt;
   (re-seq regexp string)&lt;br /&gt;
 Example&lt;br /&gt;
   (re-seq #&amp;quot;\w+&amp;quot; &amp;quot;Hello World&amp;quot;) =&amp;gt; (&amp;quot;Hello&amp;quot; &amp;quot;World&amp;quot;)  =&amp;gt; #&amp;quot;\w+&amp;quot; represents the java.util.regex.Pattern&lt;br /&gt;
&lt;br /&gt;
=== Java Interoperability ===&lt;br /&gt;
Considering Clojure, it gives clean, simple and direct access to java and can access Java API directly.Clojure doesnot wrap Java's string functions. We can call using Java interop forms. It provides syntax for accessing Java elements like classes, instances, constructors, methods and fields and can also wrap Java API. The “.” dot special form is used for accessing Java. Some Clojure syntax which can access Java API:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;2&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
!  Java&lt;br /&gt;
!  Clojure&lt;br /&gt;
|-&lt;br /&gt;
| new Widget(“red”)&lt;br /&gt;
| (new Widget “red”)&lt;br /&gt;
|-&lt;br /&gt;
| Math.PI&lt;br /&gt;
| (.Math PI) or  Math/PI&lt;br /&gt;
|-&lt;br /&gt;
| System.currentTimeMillis()&lt;br /&gt;
| (.System currentTimeMillis) or System/currentTimeMillis&lt;br /&gt;
|-&lt;br /&gt;
| rnd.nextInt()&lt;br /&gt;
| (.rnd nextInt) or (.nextInt rnd)&lt;br /&gt;
|-&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Clojure pass functions as arguments to other functions. But Java does not support this. So Clojure provides a member function memfn macro to wrap methods or can use anonymous function to wrap a method call.&lt;br /&gt;
    (map (memfn toUpperCase) [“a” ,”short”,”message”]) &lt;br /&gt;
or&lt;br /&gt;
    (map #(.toUpperCase %)[“a”,”short”,”message”]) =&amp;gt; #(body) represents the anonymous function in Clojure.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
    (def the-digits&lt;br /&gt;
    (map #(Integer. (str %))(filter #(Character/isDigit %) (seq big-num-str))))&lt;br /&gt;
 &lt;br /&gt;
     where (def big-num-str (str &amp;quot;123785334434se9088af8309304293872adbcdfd”))&lt;br /&gt;
&lt;br /&gt;
The above code extracts the integers from string and discards the non-numeric characters. Lets look at the functions defined in the example. There are totally five functions defined.They are &lt;br /&gt;
     (seq big-num-str)          =&amp;gt; get each character defined in big-num-str&lt;br /&gt;
     (Character/isDigit %)      =&amp;gt; Checks whether the input is an integer&lt;br /&gt;
     (filter #())               =&amp;gt; Filter each string from str&lt;br /&gt;
     (map #(Integer. (str %)))  =&amp;gt; Change the string to integer &lt;br /&gt;
     (def the-digits)           =&amp;gt; Output the integers only in a string of characters.     &lt;br /&gt;
Here, &lt;br /&gt;
    #(Character/isDigit) represents the Java method Character.isDigit() and #(Integer.(str %)) represents the new java.lang.Integer(str(%))&lt;br /&gt;
&lt;br /&gt;
Most of the Clojure library functions have defined semantics for objects of Java types. contains? and .get work on Java’s  Maps, arrays, Strings, count works on Java Strings, Collections and arrays. Clojure is built around these aspects. It avails the performance of JVM and the richness of both the core APIs and the numerous third-party libraries written in the Java language and restrained from reinventing them.&lt;br /&gt;
&lt;br /&gt;
=== Multiple Inheritance ===&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Multiple_inheritance Multiple Inheritance][http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf 2] is the concept of using the methods and variables of more than one superclass to a sub class.Java was designed without multiple inheritance. But Java supports the solution of problems commonly solved with multiple inheritance in other ways with help of interfaces where the methods defined in it are not implemented.In Scala, classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance in Java.Lets see how multiple inheritance achieved in Scala:&lt;br /&gt;
&lt;br /&gt;
As interfaces in Java, Scala allows traits but has some methods partially implemented. The only difference to classes is the traits may not have constructor parameters.&lt;br /&gt;
&lt;br /&gt;
  trait Similarity {&lt;br /&gt;
  def isSimilar(x: Any): Boolean   // not implemented&lt;br /&gt;
  def isNotSimilar(x: Any): Boolean = !isSimilar(x) //implemented method&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
This trait defines two methods isSimilar and isNotSimilar where isSimilar does not provide a concrete method implementation (it is abstract in the terminology of Java), and the method isNotSimilar defines a concrete implementation. Consequently, classes that integrate this trait only have to provide a concrete implementation for isSimilar. &lt;br /&gt;
&lt;br /&gt;
  class Point(xc: Int, yc: Int) extends Similarity {&lt;br /&gt;
    var x: Int = xc&lt;br /&gt;
    var y: Int = yc&lt;br /&gt;
    def isSimilar(obj: Any) =  //need to implement the method here &lt;br /&gt;
    obj.isInstanceOf[Point] &amp;amp;&amp;amp;&lt;br /&gt;
    obj.asInstanceOf[Point].x == x&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
  object TraitsTest extends Application {&lt;br /&gt;
    val p1 = new Point(2, 3)&lt;br /&gt;
    val p2 = new Point(2, 4)&lt;br /&gt;
    val p3 = new Point(3, 3)&lt;br /&gt;
    println(p1.isNotSimilar(p2))&lt;br /&gt;
    println(p1.isNotSimilar(p3))  //uses the already defined method &lt;br /&gt;
    println(p1.isNotSimilar(2))&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
These are some of the aspects and traits of mixing functional and object-oriented approaches. As we discussed in the advantages section, both the approaches have their benefits and limitations. Mixing them aspect-wise enables the above features in such languages. Lets discuss those languages briefly in the next section.&lt;br /&gt;
&lt;br /&gt;
== Languages Supporting Functional and OO code ==&lt;br /&gt;
&lt;br /&gt;
OCaml and F#[[http://msdn.microsoft.com/en-us/library/dd233154.aspx 7]] are some of the languages which support both functional and object oriented programming. OCaml is as fast as C and its featured as [http://www.haskell.org/ Haskell] which is a pure functional language. F#[[http://oreilly.com/catalog/9780596153656 3]] is a dynamically typed language which can run on .NET framework and has supported immutable types i.e. tuples, records, discriminated unions and lists  to work in Functional programming. It has functions that can either be in curried or in uncurried form. As in functional language it can pass functions as arguments to other functions, resulting in higher order functions. It also supports lambda functions and closures. F#,behaves like other .NET languages as both in imperative and object oriented style.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Clojure[[http://oreilly.com/catalog/9781934356333 10]] is also a functional programming language and it is a dialect of Lisp. It is not a pure functional language and it is a dynamically typed language. Just like Java it runs on JVM platform. But its syntax differs from Java. It is represented as :&lt;br /&gt;
&lt;br /&gt;
  (functions arguments...)&lt;br /&gt;
&lt;br /&gt;
The function followed by its arguments is enclosed in paranthesis. It has features like immutable data structures, high-order functions and recursion, easy and fast java interoperability. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Python and Ruby are also the programming languages which offer the mix of functional and OO languages. But these languages doesn't support the algebraic data types and pattern matching.&lt;br /&gt;
&lt;br /&gt;
==Conclusion ==&lt;br /&gt;
The above aspects of functional and object oriented programming techniques discuss some if their merits and demerits. Mixing them produces a new programming paradigm which leads to a new dimension in programming. A few fundamental concepts are explored in Clojure and Scala here. The ability of Clojure and Scala to run in JVM platform makes them more preferable than others in the market. Some of the merits like closure, less verbosity, high order functions, currying along with interoperation with previously written libraries in these languages make them more efficient and useful. There are also other languages which support functional and object oriented techniques. Mixing the approaches, evolve a new dimension in programming which is practical and opens doors to more exploration.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&lt;br /&gt;
# [http://www.scala-lang.org/node/1305 Bagwell. Learning Scala. Available from http://www.scala-lang.org/node/1305 (2009); Accessed 24 April 2010.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.4735&amp;amp;rep=rep1&amp;amp;type=pdf  Bjarne Stroustrup. Multiple Inheritance for C++. 1999.]&lt;br /&gt;
# [http://oreilly.com/catalog/9780596153656 Chris Smith. Programming F#. O'Reilly Media, Sebastopol, CA, 2009.]&lt;br /&gt;
# [http://portal.acm.org/citation.cfm?id=1074217 Jean E. Sammet, David Hemmendinger. Encyclopedia of Computer Science. John Wiley and Sons Ltd., Chicester, UK, 2003.]&lt;br /&gt;
# [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf Jeremiah Willcock, Jaakko Jarvi, Doug Gregor, Bjarne Stroustrup, Andrew Lumsdaine. Lambda expressions and closures for C++. 2006.]&lt;br /&gt;
# [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.56.1464&amp;amp;rep=rep1&amp;amp;type=pdf Lee Braine. An Object-Oriented Functional Approach to Information Systems Engineering, Department of Computer Science, University College London.]&lt;br /&gt;
# [http://msdn.microsoft.com/en-us/library/dd233154.aspx Microsoft Corporation. Visual F#. Available from http://msdn.microsoft.com/en-us/library/dd233154.aspx (2010)]&lt;br /&gt;
# [http://www.jot.fm/issues/issue_2009_09/article5.pdf Ph. Narbel. Functional Programming at Work in Object-Oriented Programming. ETH Zurich, Chair of Software Engineering, Journal of Object Technology, 2009. Vol. 8, No. 6.]&lt;br /&gt;
# [http://www.cs.purdue.edu/homes/jv/510s05/papers/shriram-ecoop98.pdf Shriram Krishnamurthi, Matthias Felleisen, Daniel P. Friedman. Synthesizing Object-Oriented and Functional Design to Promote Re-use. European Conference on Object-Oriented Programming, 1998.]&lt;br /&gt;
# [http://oreilly.com/catalog/9781934356333 Stuart Hallway. Programming Clojure. Pragmatic Bookshelf, USA, 2009.]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=62895</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=62895"/>
		<updated>2012-09-07T18:54:49Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Under construction :)&lt;br /&gt;
&lt;br /&gt;
= Level 1 =&lt;br /&gt;
asdf&lt;br /&gt;
== Level 2 ==&lt;br /&gt;
asfd&lt;br /&gt;
=== Level 3 ===&lt;br /&gt;
asdf&lt;br /&gt;
&lt;br /&gt;
= Another Level 1 =&lt;br /&gt;
&lt;br /&gt;
= For good measure =&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=62894</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=62894"/>
		<updated>2012-09-07T18:54:18Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Under construction :)&lt;br /&gt;
&lt;br /&gt;
= Level 1 =&lt;br /&gt;
asdf&lt;br /&gt;
== Level 2 ==&lt;br /&gt;
asfd&lt;br /&gt;
=== Level 3 ===&lt;br /&gt;
asdf&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012&amp;diff=62893</id>
		<title>CSC/ECE 517 Fall 2012</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012&amp;diff=62893"/>
		<updated>2012-09-07T18:49:06Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*[[CSC/ECE 517 Fall 2012/ch1 n xx]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w1 rk]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w20 pp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w6 pp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w8 aa]]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=62892</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w8 aa</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w8_aa&amp;diff=62892"/>
		<updated>2012-09-07T18:48:19Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: Created page&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Under construction :)&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_506_Spring_2011/ch10a_dc&amp;diff=44919</id>
		<title>CSC/ECE 506 Spring 2011/ch10a dc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_506_Spring_2011/ch10a_dc&amp;diff=44919"/>
		<updated>2011-04-14T18:25:18Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Chapter 10a Supplement - Java Memory Model&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
This chapter supplement discusses the [http://rsim.cs.illinois.edu/Pubs/popl05.pdf Java Memory Model] (JMM). First of all, we will cover the motivation for a memory model for Java. Secondly, the main aspects of JMM including happens-before relationships and final and volatile variables. And lastly, we'll mention double-checking.&lt;br /&gt;
&lt;br /&gt;
=Motivation=&lt;br /&gt;
&lt;br /&gt;
With [http://en.wikipedia.org/wiki/Parallel_computing parallel computing] becoming more popular, programming languages face many challenges including:&lt;br /&gt;
&lt;br /&gt;
* multiple layers of cache across different processors (this introduces problems with [http://en.wikipedia.org/wiki/Cache_consistency cache consistancy])&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Data_race data races] (that is, when two threads try to access the data at the same time when it is being altered by another thread)&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Synchronization_(computer_science) synchronization] directives. Note: these may be different depending on whether you have a &amp;quot;strong&amp;quot; or &amp;quot;weak&amp;quot; memory model (see pages 290-313 in chapter 10 of Solihin's textbook, &amp;quot;Fundamentals of Parallel Computer Architecture)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
* compiler reordering of instructions (part of [http://en.wikipedia.org/wiki/Compiler_optimization compiler optimization])&lt;br /&gt;
&lt;br /&gt;
Programmers need to know how these issues effect program execution so that they can write good software for parallel systems. For example, C/C++ has the [https://computing.llnl.gov/tutorials/pthreads/ pthreads] add-on to handle parallel programing. However, Java supports parallel programing by default. The JMM describes what is legal behavior for variables and memory accesses in programs with multiple threads.&lt;br /&gt;
&lt;br /&gt;
=Main Aspects=&lt;br /&gt;
&lt;br /&gt;
One of the most important parts of the Java Memory Model is the concept of [http://en.wikipedia.org/wiki/Happened-before &amp;quot;happens-before.&amp;quot;] Two statements have a happens-before relationship if one must come before the other. &lt;br /&gt;
&lt;br /&gt;
==Happens-before Illustration==&lt;br /&gt;
For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// Thread 1&lt;br /&gt;
int xIsWritten = 0;&lt;br /&gt;
x = 1;&lt;br /&gt;
xIsWritten = 1;&lt;br /&gt;
&lt;br /&gt;
// Thread 2&lt;br /&gt;
while(xIsWritten) {&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example it is important that the statement &amp;lt;tt&amp;gt;x = 1&amp;lt;/tt&amp;gt; is completed before &amp;lt;tt&amp;gt;xIsWritten = 1&amp;lt;/tt&amp;gt;, and that this order is seen by both threads. In other words, &amp;lt;tt&amp;gt;x = 1&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;xIsWritten&amp;lt;/tt&amp;gt; need to have a happens-before relationship. &lt;br /&gt;
&lt;br /&gt;
==Happens-before Rules==&lt;br /&gt;
Brian Goetz in [http://www2.lib.ncsu.edu/catalog/record/NCSU2282669 Java Concurrency in Practice] explains that happens-before relationships require the following rules: &lt;br /&gt;
&lt;br /&gt;
* Program order rule - the order that statements are written in should be the order that every processor sees them executed in.&lt;br /&gt;
&lt;br /&gt;
* Monitor lock rule - only one thread at a time is allowed to work on a synchronized method or block of code (synchronized means that it is protected by a monitor). Whenever a thread wants to enter a synchronized block of code it must acquire a lock (the monitor). The monitor lock rule insures that ever lock and unlock on the monitor is done in order. A monitor is like a key that a thread must get before it can access a synchronized method or block of code, and only one thread can have the key at any one time. Example code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// synchronized method&lt;br /&gt;
public synchronized insertLinkedList(int * element)  &lt;br /&gt;
{ // each thread must acquire the monitor associated with the method&lt;br /&gt;
  // here before executing the rest of the code&lt;br /&gt;
    &lt;br /&gt;
  // ... code to insert element into linked list&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// synchronized block&lt;br /&gt;
String myObj;&lt;br /&gt;
synchronized(myObj) &lt;br /&gt;
{ // each thread must acquire the monitor associated with the object&lt;br /&gt;
  // before executing the rest of the code.&lt;br /&gt;
&lt;br /&gt;
  // ... critical code here&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Note:&amp;lt;/b&amp;gt; any java object regardless of type has a monitor associated with it which can be used to synchronize a block of code via &amp;lt;tt&amp;gt;synchronized(myObj)&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
* Volatile variable rule - volatile variable rule says that a volatile variable is synchronized like a synchronized block of code or method is. In other words, only one thread at a time can write or read a volatile variable.&lt;br /&gt;
&lt;br /&gt;
* Thread start rule - this ensures that insures that a thread can't start executing code before it has been properly set up (i.e. the call to Thread.start() has finished).&lt;br /&gt;
&lt;br /&gt;
* Thread termination rule - this ensures that before a thread is terminated every other thread sees the result of the terminating thread's instructions.&lt;br /&gt;
&lt;br /&gt;
* Interruption rule - one thread must complete the process of calling an interrupt on the other thread before the other thread starts servicing the interrupt.&lt;br /&gt;
&lt;br /&gt;
* Finalizer rule - this ensures that the constructor finishes constructing the thread before the finalizer starts.&lt;br /&gt;
&lt;br /&gt;
* Transitivity - ensures that [http://en.wikipedia.org/wiki/Transitive_relation transitive relationships] are kept. For example, if A follows B and C follows B then C *must* follow A.&lt;br /&gt;
&lt;br /&gt;
These rules are the main framework for the Java programming model.&lt;br /&gt;
==Volatile and Final Variables==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Volatile_variable#In_Java Volatile] and [http://en.wikipedia.org/wiki/Final_(Java) final] variables are also important to the JMM. As mentioned above in the happens-before rules, volatile variables may only be written or read by one thread at a time. Reads and writes to them have a global order. This is critical for global variables that may be written by more than one thread. On the other hand, a final variable can only be written once. This means that they are written once in the constructor of a object. Note that this does not imply that the variables are immutable (see reference for more information).&lt;br /&gt;
&lt;br /&gt;
=Secondary Aspects=&lt;br /&gt;
&lt;br /&gt;
Beyond the main principles of the Java Memory Model there are many details.&lt;br /&gt;
&lt;br /&gt;
==Double-checked Locking==&lt;br /&gt;
&lt;br /&gt;
One of the controversial issues that came up with parallel computing and the JMM was double-checked locking. People wanted to avoid time consuming synchronization so they implemented double-checked locking. Here is an example of double-checked locking from [http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html Jeremy Manson and Brien Goetz (2004)]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// From Manson and Goetz (2004) JSR 133 (Java Memory Model) FAQ&lt;br /&gt;
// double-checked-locking - don't do this!&lt;br /&gt;
&lt;br /&gt;
private static Something instance = null;&lt;br /&gt;
&lt;br /&gt;
public Something getInstance() {&lt;br /&gt;
  if (instance == null) {&lt;br /&gt;
    synchronized (this) {&lt;br /&gt;
      if (instance == null)&lt;br /&gt;
        instance = new Something();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  return instance;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The problem with this code is that the reads may be reordered by the compiler (they are not happens-after statements). This means the code produces indeterminate results which could lead you to attempt to read from a null pointer while thinking that it had been initialized to new Something(). This can be avoided in the new version of the JMM by declaring the instance volatile due to the volatile rule.&lt;br /&gt;
&lt;br /&gt;
A better alternative to this code is the [http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom Initialization on Demand Holder Idiom]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// From Manson and Goetz (2004) JSR 133 (Java Memory Model) FAQ&lt;br /&gt;
private static class LazySomethingHolder {&lt;br /&gt;
  public static Something something = new Something();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public static Something getInstance() {&lt;br /&gt;
  return LazySomethingHolder.something;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Summary=&lt;br /&gt;
&lt;br /&gt;
In summary the JMM is a useful and necessary tool. It's useful for programmers trying to deal with multiple threads; because, it lets them know what (and what not) to expect. The happens-after relationship allows the programmers to restrict certain instructions that must be done in order. And, the JMM is necessary because without the tools it provides for synchronization programs may have indeterminate results.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# Barney, Blaise [https://computing.llnl.gov/tutorials/pthreads/ POSIX Threads Programming]&lt;br /&gt;
# Goetz, Brian, [http://www2.lib.ncsu.edu/catalog/record/NCSU2282669 Java Concurrency in Practice]&lt;br /&gt;
# Manson and Goetz, [http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html JSR 133 (Java Memory Model) FAQ]&lt;br /&gt;
# Manson, Pugh and Adve, [http://rsim.cs.illinois.edu/Pubs/popl05.pdf The Java Memory Model]&lt;br /&gt;
# Solihin, Yan, Fundamentals of Parallel Computer Architencture&lt;br /&gt;
# Wikipedia, [http://en.wikipedia.org/wiki/Cache_consistency Cache Consistancy]&lt;br /&gt;
# Wikipedia, [http://en.wikipedia.org/wiki/Compiler_optimization Compiler Optimization]&lt;br /&gt;
# Wikipedia, [http://en.wikipedia.org/wiki/Data_race Data Race]&lt;br /&gt;
# Wikipedia, [http://en.wikipedia.org/wiki/Happened-before &amp;quot;Happened-before.&amp;quot;]&lt;br /&gt;
# Wikipeida, [http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom Initialization on Demand Holder Idiom]&lt;br /&gt;
# Wikipedia, [http://en.wikipedia.org/wiki/Parallel_computing Parallel Computing]&lt;br /&gt;
# Wikipedia, [http://en.wikipedia.org/wiki/Synchronization_(computer_science) Synchronization (computer science)]&lt;br /&gt;
# Wikipedia, [http://en.wikipedia.org/wiki/Transitive_relation Transitive Relation]&lt;br /&gt;
# Wikipedia, [http://en.wikipedia.org/wiki/Volatile_variable#In_Java Volatile Volatile Variables]&lt;br /&gt;
# Wikipedia, [http://en.wikipedia.org/wiki/Final_(Java) Final (Java)]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_506_Spring_2011/ch10a_dc&amp;diff=44918</id>
		<title>CSC/ECE 506 Spring 2011/ch10a dc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_506_Spring_2011/ch10a_dc&amp;diff=44918"/>
		<updated>2011-04-14T18:24:23Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: rewrote for clarity and added more examples and references&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Chapter 10a Supplement - Java Memory Model&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
This chapter supplement discusses the [http://rsim.cs.illinois.edu/Pubs/popl05.pdf Java Memory Model] (JMM). First of all, we will cover the motivation for a memory model for Java. Secondly, the main aspects of JMM including happens-before relationships and final and volatile variables. And lastly, we'll mention double-checking.&lt;br /&gt;
&lt;br /&gt;
=Motivation=&lt;br /&gt;
&lt;br /&gt;
With [http://en.wikipedia.org/wiki/Parallel_computing parallel computing] becoming more popular, programming languages face many challenges including:&lt;br /&gt;
&lt;br /&gt;
* multiple layers of cache across different processors (this introduces problems with [http://en.wikipedia.org/wiki/Cache_consistency cache consistancy])&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Data_race data races] (that is, when two threads try to access the data at the same time when it is being altered by another thread)&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Synchronization_(computer_science) synchronization] directives. Note: these may be different depending on whether you have a &amp;quot;strong&amp;quot; or &amp;quot;weak&amp;quot; memory model (see pages 290-313 in chapter 10 of Solihin's textbook, &amp;quot;Fundamentals of Parallel Computer Architecture)&amp;quot;&lt;br /&gt;
&lt;br /&gt;
* compiler reordering of instructions (part of [http://en.wikipedia.org/wiki/Compiler_optimization compiler optimization])&lt;br /&gt;
&lt;br /&gt;
Programmers need to know how these issues effect program execution so that they can write good software for parallel systems. For example, C/C++ has the [https://computing.llnl.gov/tutorials/pthreads/ pthreads] add-on to handle parallel programing. However, Java supports parallel programing by default. The JMM describes what is legal behavior for variables and memory accesses in programs with multiple threads.&lt;br /&gt;
&lt;br /&gt;
=Main Aspects=&lt;br /&gt;
&lt;br /&gt;
One of the most important parts of the Java Memory Model is the concept of [http://en.wikipedia.org/wiki/Happened-before &amp;quot;happens-before.&amp;quot;] Two statements have a happens-before relationship if one must come before the other. &lt;br /&gt;
&lt;br /&gt;
==Happens-before Illustration==&lt;br /&gt;
For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// Thread 1&lt;br /&gt;
int xIsWritten = 0;&lt;br /&gt;
x = 1;&lt;br /&gt;
xIsWritten = 1;&lt;br /&gt;
&lt;br /&gt;
// Thread 2&lt;br /&gt;
while(xIsWritten) {&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example it is important that the statement &amp;lt;tt&amp;gt;x = 1&amp;lt;/tt&amp;gt; is completed before &amp;lt;tt&amp;gt;xIsWritten = 1&amp;lt;/tt&amp;gt;, and that this order is seen by both threads. In other words, &amp;lt;tt&amp;gt;x = 1&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;xIsWritten&amp;lt;/tt&amp;gt; need to have a happens-before relationship. &lt;br /&gt;
&lt;br /&gt;
==Happens-before Rules==&lt;br /&gt;
Brian Goetz in [http://www2.lib.ncsu.edu/catalog/record/NCSU2282669 Java Concurrency in Practice] explains that happens-before relationships require the following rules: &lt;br /&gt;
&lt;br /&gt;
* Program order rule - the order that statements are written in should be the order that every processor sees them executed in.&lt;br /&gt;
&lt;br /&gt;
* Monitor lock rule - only one thread at a time is allowed to work on a synchronized method or block of code (synchronized means that it is protected by a monitor). Whenever a thread wants to enter a synchronized block of code it must acquire a lock (the monitor). The monitor lock rule insures that ever lock and unlock on the monitor is done in order. A monitor is like a key that a thread must get before it can access a synchronized method or block of code, and only one thread can have the key at any one time. Example code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// synchronized method&lt;br /&gt;
public synchronized insertLinkedList(int * element)  &lt;br /&gt;
{ // each thread must acquire the monitor associated with the method&lt;br /&gt;
  // here before executing the rest of the code&lt;br /&gt;
    &lt;br /&gt;
  // ... code to insert element into linked list&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// synchronized block&lt;br /&gt;
String myObj;&lt;br /&gt;
synchronized(myObj) &lt;br /&gt;
{ // each thread must acquire the monitor associated with the object&lt;br /&gt;
  // before executing the rest of the code.&lt;br /&gt;
&lt;br /&gt;
  // ... critical code here&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;b&amp;gt;Note:&amp;lt;/b&amp;gt; any java object regardless of type has a monitor associated with it which can be used to synchronize a block of code via &amp;lt;tt&amp;gt;synchronized(myObj)&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
* Volatile variable rule - volatile variable rule says that a volatile variable is synchronized like a synchronized block of code or method is. In other words, only one thread at a time can write or read a volatile variable.&lt;br /&gt;
&lt;br /&gt;
* Thread start rule - this ensures that insures that a thread can't start executing code before it has been properly set up (i.e. the call to Thread.start() has finished).&lt;br /&gt;
&lt;br /&gt;
* Thread termination rule - this ensures that before a thread is terminated every other thread sees the result of the terminating thread's instructions.&lt;br /&gt;
&lt;br /&gt;
* Interruption rule - one thread must complete the process of calling an interrupt on the other thread before the other thread starts servicing the interrupt.&lt;br /&gt;
&lt;br /&gt;
* Finalizer rule - this ensures that the constructor finishes constructing the thread before the finalizer starts.&lt;br /&gt;
&lt;br /&gt;
* Transitivity - ensures that [http://en.wikipedia.org/wiki/Transitive_relation transitive relationships] are kept. For example, if A follows B and C follows B then C *must* follow A.&lt;br /&gt;
&lt;br /&gt;
These rules are the main framework for the Java programming model.&lt;br /&gt;
==Volatile and Final Variables==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Volatile_variable#In_Java Volatile] and [http://en.wikipedia.org/wiki/Final_(Java) final] variables are also important to the JMM. As mentioned above in the happens-before rules, volatile variables may only be written or read by one thread at a time. Reads and writes to them have a global order. This is critical for global variables that may be written by more than one thread. On the other hand, a final variable can only be written once. This means that they are written once in the constructor of a object. Note that this does not imply that the variables are immutable (see reference for more information).&lt;br /&gt;
&lt;br /&gt;
=Secondary Aspects=&lt;br /&gt;
&lt;br /&gt;
Beyond the main principles of the Java Memory Model there are many details.&lt;br /&gt;
&lt;br /&gt;
==Double-checked Locking==&lt;br /&gt;
&lt;br /&gt;
One of the controversial issues that came up with parallel computing and the JMM was double-checked locking. People wanted to avoid time consuming synchronization so they implemented double-checked locking. Here is an example of double-checked locking from [http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html Jeremy Manson and Brien Goetz (2004)]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// From Manson and Goetz (2004) JSR 133 (Java Memory Model) FAQ&lt;br /&gt;
// double-checked-locking - don't do this!&lt;br /&gt;
&lt;br /&gt;
private static Something instance = null;&lt;br /&gt;
&lt;br /&gt;
public Something getInstance() {&lt;br /&gt;
  if (instance == null) {&lt;br /&gt;
    synchronized (this) {&lt;br /&gt;
      if (instance == null)&lt;br /&gt;
        instance = new Something();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  return instance;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The problem with this code is that the reads may be reordered by the compiler (they are not happens-after statements). This means the code produces indeterminate results which could lead you to attempt to read from a null pointer while thinking that it had been initialized to new Something(). This can be avoided in the new version of the JMM by declaring the instance volatile due to the volatile rule.&lt;br /&gt;
&lt;br /&gt;
A better alternative to this code is the [http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom Initialization on Demand Holder Idiom]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// From Manson and Goetz (2004) JSR 133 (Java Memory Model) FAQ&lt;br /&gt;
private static class LazySomethingHolder {&lt;br /&gt;
  public static Something something = new Something();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public static Something getInstance() {&lt;br /&gt;
  return LazySomethingHolder.something;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Summary=&lt;br /&gt;
&lt;br /&gt;
In summary the JMM is a useful and necessary tool. It's useful for programmers trying to deal with multiple threads; because, it lets them know what (and what not) to expect. The happens-after relationship allows the programmers to restrict certain instructions that must be done in order. And, the JMM is necessary because without the tools it provides for synchronization programs may have indeterminate results.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# Barney, Blaise [https://computing.llnl.gov/tutorials/pthreads/ POSIX Threads Programming]&lt;br /&gt;
# Goetz, Brian, [http://www2.lib.ncsu.edu/catalog/record/NCSU2282669 Java Concurrency in Practice]&lt;br /&gt;
# Manson and Goetz, [http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html JSR 133 (Java Memory Model) FAQ]&lt;br /&gt;
# Manson, Pugh and Adve, [http://rsim.cs.illinois.edu/Pubs/popl05.pdf The Java Memory Model]&lt;br /&gt;
# Solihin, Yan, Fundamentals of Parallel Computer Architencture&lt;br /&gt;
# Wikipedia, [http://en.wikipedia.org/wiki/Cache_consistency Cache Consistancy]&lt;br /&gt;
# Wikipedia, [http://en.wikipedia.org/wiki/Compiler_optimization Compiler Optimization]&lt;br /&gt;
# Wikipedia, [http://en.wikipedia.org/wiki/Data_race Data Race]&lt;br /&gt;
# Wikipedia, [http://en.wikipedia.org/wiki/Happened-before &amp;quot;Happened-before.&amp;quot;]&lt;br /&gt;
# Wikipeida, [http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom Initialization on Demand Holder Idiom]&lt;br /&gt;
# Wikipedia, [http://en.wikipedia.org/wiki/Parallel_computing Parallel Computing]&lt;br /&gt;
# Wikipedia, [http://en.wikipedia.org/wiki/Synchronization_(computer_science) Synchronization (computer science)]&lt;br /&gt;
# Wikipedia, [http://en.wikipedia.org/wiki/Transitive_relation Transitive Relation]&lt;br /&gt;
# Wikipedia, [[http://en.wikipedia.org/wiki/Volatile_variable#In_Java Volatile] Volatile Variables]&lt;br /&gt;
# Wikipedia, [http://en.wikipedia.org/wiki/Final_(Java) Final (Java)]&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_506_Spring_2011/ch2_dm&amp;diff=44910</id>
		<title>CSC/ECE 506 Spring 2011/ch2 dm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_506_Spring_2011/ch2_dm&amp;diff=44910"/>
		<updated>2011-04-11T22:04:41Z</updated>

		<summary type="html">&lt;p&gt;Dmcarmon: Edited due to feedback&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Supplement to Chapter 2: The Data Parallel Programming Model=&lt;br /&gt;
&lt;br /&gt;
Chapter 2 of [[#References | Solihin (2008)]] covers the shared memory and message passing parallel programming models.  However, it does not address the [http://portal.acm.org/citation.cfm?id=1239917 data parallel] model (a model composed of a set of identical tasks which operate on different subsets of common data), another commonly recognized parallel programming model covered in other treatments like [http://www.mcs.anl.gov/~itf/dbpp/ Foster (1995)] and [[#References | Culler (1999)]].  &lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
The data parallel programming model (mentioned in conference proceedings as early as [http://portal.acm.org/citation.cfm?id=642120 1974]) is a programming model for SIMD (Single Instruction, Multiple Data) parallel machines.  It's defined as multiple processing elements performing an action simultaneously on different parts of a data set and exchanging information globally before processing more code synchronously.  Although the shared memory and message passing models are often presented as competing models, the data parallel model addresses fundamentally different programming concerns and can be used in conjunction with either.  The main distinction between the data parallel model and the other two models has to do with the outcome of the individual steps instead of the method of communication.  The data parallel model was developed for scientific calculations and is generally associated with applications that involve a data set which is typically organized into a common structure, such as an array or matrix.  Data parallel processing has been found to be effective in situations where the computations allow the processing to be divided spatially over memories by involving every element of a matrix in a uniform way.&lt;br /&gt;
  &lt;br /&gt;
In addition to the data parallel model, the task parallel model (a model composed of a set of differing tasks which operate on common data.) will also be introduced briefly in [[#Appendix_B:_Data_Parallel_Versus_Task-parallel | Appendix B]] as a point of contrast with the data-parallel model. Furthermore, we will discuss the role of the shared memory and message passing models in the history of parallel computing. The goal of this supplement is to provide a treatment of the data parallel model which complements Chapter 2 of [[#References | Solihin (2008)]].&lt;br /&gt;
&lt;br /&gt;
=Examples with the Data Parallel Model, Shared Memory, and Message Passing=&lt;br /&gt;
&lt;br /&gt;
While the [http://www.cs.cf.ac.uk/Parallel/Year2/section4.html shared memory and message passing] models focus on how parallel tasks access common data, the data parallel model focuses on how to divide up work into parallel instructions.  Data parallel algorithms exploit parallelism by dividing a problem into a number of identical instructions which execute on different subsets of common data.  &lt;br /&gt;
&lt;br /&gt;
==Preliminary Example==&lt;br /&gt;
&lt;br /&gt;
A supporting example of a data parallel code can be seen in Code 2.5 from [[#References | Solihin (2008)]]. Shown below, it has been annotated with comments identifying the region of the code which is data parallel.&lt;br /&gt;
&lt;br /&gt;
 // Data parallel code, adapted from [[#References|Solihin (2008), p. 27.]]&lt;br /&gt;
 &lt;br /&gt;
 id = getmyid(); // Assume id = 0 for thread 0, id = 1 for thread 1&lt;br /&gt;
 local_iter = 4;&lt;br /&gt;
 start_iter = id * local_iter;&lt;br /&gt;
 end_iter = start_iter + local_iter;&lt;br /&gt;
 &lt;br /&gt;
 if (id == 0)&lt;br /&gt;
     send_msg(P1, b[4..7], c[4..7]);&lt;br /&gt;
 else&lt;br /&gt;
     recv_msg(P0, b[4..7], c[4..7]);&lt;br /&gt;
 &lt;br /&gt;
 // Begin data parallel section&lt;br /&gt;
 &lt;br /&gt;
 for (i = start_iter; i &amp;lt; end_iter; i++)&lt;br /&gt;
     a[i] = b[i] + c[i];&lt;br /&gt;
 local_sum = 0;&lt;br /&gt;
 for (i = start_iter; i &amp;lt; end_iter; i++)&lt;br /&gt;
     if (a[i] &amp;gt; 0)&lt;br /&gt;
         local_sum = local_sum + a[i];&lt;br /&gt;
 &lt;br /&gt;
 // End data parallel section&lt;br /&gt;
 &lt;br /&gt;
 if (id == 0)&lt;br /&gt;
 {&lt;br /&gt;
     recv_msg(P1, &amp;amp;local_sum1);&lt;br /&gt;
     sum = local_sum + local_sum1;&lt;br /&gt;
     Print sum;&lt;br /&gt;
 }&lt;br /&gt;
 else&lt;br /&gt;
     send_msg(P0, local_sum);&lt;br /&gt;
&lt;br /&gt;
In the code above, the three 8 element arrays are each divided into two 4 element chunks.  In the data parallel section, the code executed by the two threads is identical, but each thread operates on a different chunk of data.&lt;br /&gt;
&lt;br /&gt;
==Main Example==&lt;br /&gt;
&lt;br /&gt;
Our main example is as follows. Suppose we want to perform the following operation on an array &amp;lt;code&amp;gt;a&amp;lt;/code&amp;gt;: updating each element of &amp;lt;code&amp;gt;a&amp;lt;/code&amp;gt; by the product of itself and its index, and adding together the elements of &amp;lt;code&amp;gt;a&amp;lt;/code&amp;gt; into the variable &amp;lt;code&amp;gt;sum&amp;lt;/code&amp;gt;. The corresponding code is shown below.&lt;br /&gt;
&lt;br /&gt;
 // simple sequential operation&lt;br /&gt;
 sum = 0;&lt;br /&gt;
 '''for''' (i = 0; i &amp;lt; a.length; i++)&lt;br /&gt;
 {&lt;br /&gt;
    a[i] = a[i] * i;&lt;br /&gt;
    sum = sum + a[i];&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
When we orchestrate the operation using the data parallel programming model, the program can be divided into two parts. The first part performs the same operations on separate elements of the array for each processing element (sometimes referred to as PE).  The second part reorganizes data among all processing elements (In our example data reorganization is summing up values across different processing elements). &lt;br /&gt;
&lt;br /&gt;
===First Part: Decomposition===&lt;br /&gt;
&lt;br /&gt;
The data parallel programming model defines the overall effects of parallel steps for the first part.  [[#References | Hillis (1986)]] points out that a major benefit of data parallel algorithms is that they easily scale to take advantage of additional processing elements simply by dividing the data into smaller chunks.  [[#References | Haveraaen (2000)]] also notes that data parallel codes typically bear a strong resemblance to sequential codes, making them easier to read and write.  &lt;br /&gt;
&lt;br /&gt;
The three code fragments below are examples for the first part of the program, shared-memory version of the second part, and message passing for the second part, respectively.&lt;br /&gt;
&lt;br /&gt;
 // data parallel programming: let each PE perform the same operation on different pieces of distributed data&lt;br /&gt;
 pe_id = getid();&lt;br /&gt;
 my_sum = 0;&lt;br /&gt;
 '''for''' (i = pe_id; i &amp;lt; a.length; i += number_of_pe)         //separate elements of the array are assigned to each PE &lt;br /&gt;
 {&lt;br /&gt;
    a[i] = a[i] * i;&lt;br /&gt;
    my_sum = my_sum + a[i];                               //all PEs accumulate elements assigned to them into local variable my_sum&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above code, data parallelism is achieved by letting each processing element perform actions on array's separate elements, which are identified using the PE's id (&amp;lt;tt&amp;gt;pe_id&amp;lt;/tt&amp;gt;. For instance, if three processing elements are used then one processing element would start at &amp;lt;tt&amp;gt;i = 0&amp;lt;/tt&amp;gt;, one would start at &amp;lt;tt&amp;gt;i = 1&amp;lt;/tt&amp;gt;, and the last would start at &amp;lt;tt&amp;gt;i = 2&amp;lt;/tt&amp;gt;. Since there are three processing elements, the index of the array for each will increase by three on each iteration until the operation is complete (note that in our example elements assigned to each PE are interleaved instead of continuous). If the length of the array is a multiple of three then each processing element takes the same amount of time to execute its portion of the operation.&lt;br /&gt;
&lt;br /&gt;
The picture below illustrates how elements of the array are assigned among different PEs for the specific case: length of the array is 7 and there are 3 PEs available. Elements in the array are marked by their indexes (0 to 6). As shown in the picture, PE0 will work on elements with index 0, 3, 6; PE1 is in charge of elements with index 1, 4; and elements with index 2, 5 are assigned to PE2. In this way, these 3 PEs work collectively on the array, while each PE works on different elements. Thus, data parallelism is achieved.&lt;br /&gt;
&lt;br /&gt;
[[Image:506wiki1.png|frame|center|150px|Illustration of data parallel programming(adapted from [http://computing.llnl.gov/tutorials/parallel_comp/#ModelsData Introduction to Parallel Computing])]]&lt;br /&gt;
&lt;br /&gt;
===Second Part: Orchestration===&lt;br /&gt;
&lt;br /&gt;
The second part can be accomplished either through shared memory or message passing.  The code below shows how data reorganization is done by the shared memory programming model.  A shared variable is declared to store the global sum.  Each PE accumulates their local my_sum into this variable.  In this example, the &amp;lt;tt&amp;gt;lock()&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;unlock()&amp;lt;/tt&amp;gt; routines are used to prevent race conditions and barrier ensures that all the local &amp;lt;tt&amp;gt;my_sum&amp;lt;/tt&amp;gt; variables have been accumulated into the shared variable &amp;lt;tt&amp;gt;sum&amp;lt;/tt&amp;gt; before the code proceeds.  Notice that in this model there is only one copy of the data like in the data parallel model.  However, in the shared memory model, the data must be protected since any PE could be using it at any point, whereas data is associated with a specific PE in the data parallel model.&lt;br /&gt;
&lt;br /&gt;
 // data reorganization via shared memory&lt;br /&gt;
 '''shared''' sum;&lt;br /&gt;
 lock();                                                  //prevent race condition&lt;br /&gt;
 sum = sum + my_sum;                                      //each PE adds up their local my_sum to shared variable sum &lt;br /&gt;
 unlock();&lt;br /&gt;
 barrier;&lt;br /&gt;
&lt;br /&gt;
The following section of code shows how data reorganization is done by the message passing programming model.  PE0 acts as the one that collects the local my_sum variable from all the other PEs. This is done by the &amp;lt;tt&amp;gt;send_msg()&amp;lt;/tt&amp;gt; and  the &amp;lt;tt&amp;gt;recv_msg()&amp;lt;/tt&amp;gt; routines: PEs other than PE0 send their my_sum variable as a message to PE0.  PE0 receives the messages by specifying the sender in the '''for''' loop.  PE ids are used in the message passing model in the same way they are in the data parallel model.  On the contrary, in the data parallel model there is only one copy of data that is processed and there is no need to do any final accumulation by a single PE.&lt;br /&gt;
&lt;br /&gt;
 // data reorganization via message passing&lt;br /&gt;
 '''if''' (pe_id != 0) send_msg (0, my_sum);                    //PE other than PE0 send their local my_sum&lt;br /&gt;
 '''else'''                                                     //PE0 does this&lt;br /&gt;
 {&lt;br /&gt;
    '''for''' (i = 1; i &amp;lt; number_of_pe; i++)                    //for each other PE&lt;br /&gt;
    {&lt;br /&gt;
       recv_msg (i, temp);                                //receive local sum from other PEs&lt;br /&gt;
       my_sum = my_sum + temp;                            //accumulate into total&lt;br /&gt;
    }&lt;br /&gt;
    sum = my_sum;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=History of Parallel Programming Models=&lt;br /&gt;
&lt;br /&gt;
==Superscalar Machines==&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Superscalar superscalar] processor is a pipelined processor able to retire multiple instructions in one cycle. The first superscalar machine was Cray's CDC 6600. It was released in 1964 and could execute 1 million floating point operations per second (1 MFLOP). &lt;br /&gt;
&lt;br /&gt;
The CDC 6600 gained most of its speed through delegating memory access and I/O to other processors, handling only arithmetic and logic. These peripheral processors, and the main CPU, could be designed to be as simple as possible. The CDC 6600 remained the world's fastest computer until 1969, being replaced by the CDC 7600.&lt;br /&gt;
&lt;br /&gt;
==Vector Machines==&lt;br /&gt;
&lt;br /&gt;
First appearing in the late 1960s, [http://en.wikipedia.org/wiki/Vector_processor vector machines] were able to apply a single instruction to multiple data values. This type of operation is used frequently in scientific fields or in multimedia. &lt;br /&gt;
&lt;br /&gt;
The Solomon project at Westinghouse was one of the first machines to use vector operations. &lt;br /&gt;
Its CPU had a large number of ALUs that would each be fed different data each cycle. &lt;br /&gt;
Solomon was unsuccessful and was cancelled, eventually to be reborn as the [http://research.microsoft.com/en-us/um/people/gbell/computer_structures__readings_and_examples/00000340.htm ILLIAC IV] at the University of Illinois. The ILLIAC IV showed great success at solving data-intensive problems, peaking at 150 MFLOPS under the right conditions. &lt;br /&gt;
&lt;br /&gt;
An innovation came with the [http://en.wikipedia.org/w/index.php?title=Cray-1&amp;amp;oldid=409177730 Cray-1] supercomputer in 1976. The innovation stemmed from the fact that the large data sets are often manipulated by several instructions back-to-back, such as an addition followed by a multiplication. The [http://en.wikipedia.org/wiki/Instruction_pipeline instruction pipeline] of the Cray-1 was tweaked to take advantage of this using [http://people.engr.ncsu.edu/efg/506/s01/lectures/notes/lec28.pdf vector chaining]. In the ILLIAC, up to 64 data points were loaded from memory with every instruction, but had to be stored back to manipulate the rest of the vector. The Cray computer was only able to load 12 data points, but by completing multiple instructions before continuing the total number of memory accesses decreased. &lt;br /&gt;
In addition, the Cray-1 could perform at 240 MFLOPS. There continued to be new editions of Cray computers, the[http://en.wikipedia.org/wiki/Cray-2, Cray-2], [http://en.wikipedia.org/wiki/Cray-3 Cray-3] etc. One of the most recent versions, [http://en.wikipedia.org/wiki/Cray-YMP Cray Y-MP], was sold from 1988 and used a MIMD architecture.&lt;br /&gt;
&lt;br /&gt;
One of the later vector machines was the [http://www.museumwaalsdorp.nl/computer/en/comp891E.html ETA10]. It had shared memory 4M words and common memory 8M words, where each word was 64 bits. It was clocked at 24ns, but had a theorectical peak speed of 146 Mflops.&lt;br /&gt;
&lt;br /&gt;
Many of these early machines were shared memory machines. This is likely because the shared memory machines offer a easier to work with programming model and they had small enough systems that they did not worry about scallability. Also, memory was very expensive and message passing requires multiple copies of data.&lt;br /&gt;
&lt;br /&gt;
==Connection Machines==&lt;br /&gt;
&lt;br /&gt;
[http://longnow.org/essays/richard-feynman-connection-machine/ The connection machine] was a data parallel machine built in the 1980s. A connection machine had on the order of 64,000 processors. Each processor computed one bit of data and was connected to others via hypercube wiring. [http://www.mission-base.com/tamiko/cm/index.html Tamiko Thiel] describes the machine as being modeled after a human brain. The second connection machine (CM-2) which had more RAM and included floating point adders [http://en.wikipedia.org/wiki/Connection_Machine] came out in 1987, and two smaller editions, the CM-2a and the CM-200, were developed later.&lt;br /&gt;
&lt;br /&gt;
==Distributed Memory and Message Passing==&lt;br /&gt;
&lt;br /&gt;
In the 1980s, a manufacturing limit led to increased support for multiprocessor systems. The [http://en.wikipedia.org/wiki/Transputer transputer] architecture by Inmos was one of the first general-purpose microprocessors designed for parallel computing. The first transputers were released in 1984. Transputers were designed to be easily interlinkable; multiple processing chips could be easily combined into one system.&lt;br /&gt;
&lt;br /&gt;
Each transputer processor could communicate with up to four other processors at up to 20 Mbps. Any number of processors could be combined into a massive processing farm. Of course, in large nets, the delay would be too great for any significant message passing.&lt;br /&gt;
&lt;br /&gt;
==Recent Data Parallel Computing==&lt;br /&gt;
&lt;br /&gt;
Today data parallelism is most commonly done in GPUs, due to the nature of graphics computation. Because GPUs often share memory with the main computer processor and other elements, they most commonly have a  [http://en.wikipedia.org/wiki/Shared_Memory_Architecture shared memory architecture]. The supplement for [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_506_Spring_2011/ch2a_mc chapter 2a] discusses GPUs in depth.&lt;br /&gt;
&lt;br /&gt;
=Summary=&lt;br /&gt;
&lt;br /&gt;
Through the history of parallel computing we may observe the tradeoffs between the shared memory and message passing models. In the beginning, due to parallel programming being done for the most part exclusively on expensive and custom-made super computers, shared memory systems made sense. Later on, the invention of the personal computer and wider availability of smaller and less expensive computers led more people to a message passing approach. Furthermore, the message passing approach scales better. Most recently, data parallelism has been done with GPUs. Although shared-memory and message-passing models may be combined into hybrid approaches, the two models are fundamentally different ways of addressing the same problem (of access control to common data).  In contrast, the data parallel model is concerned with a fundamentally different problem (how to divide work into parallel tasks).  As such, the data parallel model may be used in conjunction with either the shared memory or the message passing model without conflict.  In fact, [[#References | Klaiber (1994)]] compares the performance of a number of data parallel programs implemented with both shared memory and message passing models.&lt;br /&gt;
&lt;br /&gt;
One of the major advantages of combining the data parallel and message passing models is a reduction in the amount and complexity of communication required relative to a task parallel approach.  Similarly, combining the data parallel and shared memory models tends to simplify and reduce the amount of synchronization required.  If the task parallel code given in the appendix were modified from a message passing model to a shared memory model, the two threads would require 8 signals be sent between the threads (instead of 8 messages).  In contrast, the data parallel code would require a single barrier before the local sums are added to compute the full sum.&lt;br /&gt;
&lt;br /&gt;
Much as the shared memory model can benefit from specialized hardware, the data parallel programming model can as well.  [http://en.wikipedia.org/wiki/SIMD SIMD (single-instruction-multiple-data)] processors are specifically designed to run data parallel algorithms.  These processors perform a single instruction on many different data locations simultaneously.  Modern examples include [http://en.wikipedia.org/wiki/CUDA CUDA processors] developed by nVidia and [http://en.wikipedia.org/wiki/Cell_%28microprocessor%29 Cell processors] developed by STI (Sony, Toshiba, and IBM).  For the curious, example code for CUDA processors is provided in the [[#Appendix C: C for CUDA Example Code | Appendix]].  However, whereas the shared memory model can be a difficult and costly abstraction in the absence of hardware support, the data parallel model&amp;amp;mdash;like the message passing model&amp;amp;mdash;does not require hardware support.&lt;br /&gt;
&lt;br /&gt;
Since data parallel code tends to simplify communication and synchronization, data parallel code may be easier to develop than a more task parallel approach. Once written, data parallel programs can scale easily to large numbers of processors.  The data parallel model implicitly encourages data locality by having each thread work on a chunk of data, and the regular data chunks also make it easier to reason about where to locate data and how to organize it. On the other hand, it is possible that a problem may not decompose easily into subproblems relying on largely independent chunks of data.  In this case, it may be impractical or impossible to apply the data parallel model.&lt;br /&gt;
&lt;br /&gt;
The table below is extended from Table 2.1 on page 22 of the Solihin text.  A column has been added for the data parallel model.  The table compares some key characteristics of each programming model.  As you can see, the complexity of the data parallel model comes mainly in the form of dividing up the work among PEs.  Most of this work is done by the programmer and does not necessarily require special hardware, although, specific types of hardware can optimize the benefits of the model.  For instance,  SIMD and SPMD (single program, multiple data) hardware are examples that have efficiently utilized the data parallel model.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| align=&amp;quot;center&amp;quot; class=&amp;quot;wikitable&amp;quot; style=&amp;quot;text-align:center;&amp;quot; border=&amp;quot;1&amp;quot; !cellpadding = &amp;quot;2&amp;quot;&lt;br /&gt;
|+ &lt;br /&gt;
! Aspects !! Data-Parallel !! Shared Memory !! Message Passing&lt;br /&gt;
|-&lt;br /&gt;
! Communication&lt;br /&gt;
| implicit - via loads/stores || implicit - via loads/stores || explicit messages&lt;br /&gt;
|-&lt;br /&gt;
! Synchronization&lt;br /&gt;
| none || explicit || implicit - via messages&lt;br /&gt;
|-&lt;br /&gt;
! Hardware support&lt;br /&gt;
| none || typically required || none&lt;br /&gt;
|-&lt;br /&gt;
! Development effort&lt;br /&gt;
| low || low || high&lt;br /&gt;
|- &lt;br /&gt;
! Tuning effort&lt;br /&gt;
| high || high || low&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=Definitions=&lt;br /&gt;
&lt;br /&gt;
* ''Data parallel.''  A data parallel algorithm is composed of a set of identical tasks which operate on different subsets of common data.&lt;br /&gt;
* ''Task parallel.''  A task parallel algorithm is composed of a set of differing tasks which operate on common data.&lt;br /&gt;
* ''SIMD (single-instruction-multiple-data).''  A processor which executes a single instruction simultaneously on multiple data locations.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
* Alexander C. Klaiber and Henry M. Levy, [http://portal.acm.org/citation.cfm?id=192020 &amp;quot;A comparison of message passing and shared memory architectures for data parallel programs,&amp;quot;] in ''Proceedings of the 21st Annual International Symposium on Computer Architecture,'' April 1994, pp. 94-105.&lt;br /&gt;
&lt;br /&gt;
* Barnes et al., [http://research.microsoft.com/en-us/um/people/gbell/computer_structures__readings_and_examples/00000340.htm The ILLIAC IV Computer]&lt;br /&gt;
* Björn Lisper, ''Data parallelism and functional programming'', Lecture Notes in Computer Science, Volume 1132/1996, pp. 220-251, Springer Berlin, 1996.&lt;br /&gt;
&lt;br /&gt;
* Blaise Barney, &amp;quot;Introduction to Parallel Computing: Data Parallel Model&amp;quot;, Lawrence Livermore National Laboratory, [https://computing.llnl.gov/tutorials/parallel_comp/#ModelsData https://computing.llnl.gov/tutorials/parallel_comp/#ModelsData], January 2009.&lt;br /&gt;
&lt;br /&gt;
* Computations Science Education Project, [http://www.phy.ornl.gov/csep/ca/node24.html Vector Processors]&lt;br /&gt;
&lt;br /&gt;
* ''C.mmp - A multi-mini-processor'', W. A. Wulf and C. G. Bell, C-MU 1972 http://research.microsoft.com/en-us/um/people/gbell/CGB%20Files/Cmmp%20Multi-Mini-Processor%20ComConference%201972%20c.pdf&lt;br /&gt;
&lt;br /&gt;
* [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_506_Spring_2011/ch2a_mc CSC/ECE_506_Spring_2011/ch2a_mc]&lt;br /&gt;
&lt;br /&gt;
* David E. Culler, Jaswinder Pal Singh, and Anoop Gupta, ''Parallel Computer Architecture: A Hardware/Software Approach'', Gulf Professional Publishing, August 1998.&lt;br /&gt;
&lt;br /&gt;
* David E. Culler, Jaswinder Pal Singh, and Anoop Gupta, [http://portal.acm.org/citation.cfm?id=550071 ''Parallel Computer Architecture: A Hardware/Software Approach,''] Morgan-Kauffman, 1999.&lt;br /&gt;
&lt;br /&gt;
* Gehringer, Ed, [http://people.engr.ncsu.edu/efg/506/s01/lectures/notes/lec28.pdf Vector Chaining]&lt;br /&gt;
&lt;br /&gt;
* Guy Blelloch, &amp;quot;Is Parallel Programming Hard?&amp;quot;, Carnegie Mellon University, [http://www.cilk.com/multicore-blog/bid/9108/Is-Parallel-Programming-Hard http://www.cilk.com/multicore-blog/bid/9108/Is-Parallel-Programming-Hard], April 2009.&lt;br /&gt;
&lt;br /&gt;
* History of Cluster Computing http://cunday.blogspot.com/2009/01/history-of-cluster-computing.html&lt;br /&gt;
&lt;br /&gt;
* Ian Foster, [http://www.mcs.anl.gov/~itf/dbpp/ ''Designing and Building Parallel Programs,''] Addison-Wesley, 1995.&lt;br /&gt;
&lt;br /&gt;
* Magne Haveraaen, [http://portal.acm.org/citation.cfm?id=1239917 &amp;quot;Machine and collection abstractions for user-implemented data-parallel programming,&amp;quot;] ''Scientific Programming,'' 8(4):231-246, 2000.&lt;br /&gt;
&lt;br /&gt;
* Philip J. Hatcher, Michael Jay Quinn, ''Data-Parallel Programming on MIMD Computers'', The MIT Press, 1991.&lt;br /&gt;
&lt;br /&gt;
*Radoy and Lipovski, [http://portal.acm.org/citation.cfm?id=642120 &amp;quot;Switched multiple instruction, multiple data stream processing&amp;quot;, ISCA '75 Proceedings of the 2nd annual symposium on Computer architecture]   &lt;br /&gt;
&lt;br /&gt;
* Shared Memory and Message Passing http://www.cs.cf.ac.uk/Parallel/Year2/section4.html&lt;br /&gt;
&lt;br /&gt;
* ''The period 1989 - 1994: ETA and CONVEX: between -40 and +40 Centigrade'' http://www.museumwaalsdorp.nl/computer/en/comp891E.html&lt;br /&gt;
&lt;br /&gt;
* W. Daniel Hillis and Guy L. Steele, Jr., [http://portal.acm.org/citation.cfm?id=7903 &amp;quot;Data parallel algorithms,&amp;quot;] ''Communications of the ACM,'' 29(12):1170-1183, December 1986.&lt;br /&gt;
&lt;br /&gt;
* Yan Solihin, ''Fundamentals of Parallel Computer Architecture: Multichip and Multicore Systems'', Solihin Books, August 2009.&lt;br /&gt;
* Wikipedia, IBM Personal Computer [http://en.wikipedia.org/wiki/IBM_Personal_Computer]&lt;br /&gt;
&lt;br /&gt;
* Wikipedia, C.mmp [http://en.wikipedia.org/wiki/C.mmp]&lt;br /&gt;
&lt;br /&gt;
* Wikipedia, CDC 6600 [http://en.wikipedia.org/wiki/CDC_6600]&lt;br /&gt;
&lt;br /&gt;
* Wikipedia, Computer Cluster [http://en.wikipedia.org/wiki/Computer_cluster]&lt;br /&gt;
&lt;br /&gt;
* Wikipedia, Cray-1 [http://en.wikipedia.org/w/index.php?title=Cray-1&amp;amp;oldid=409177730]&lt;br /&gt;
&lt;br /&gt;
* Wikipedia, Lockstep [http://en.wikipedia.org/wiki/Lockstep_(computing) http://en.wikipedia.org/wiki/Lockstep_(computing)].&lt;br /&gt;
&lt;br /&gt;
* Wikipedia, MIMD [http://en.wikipedia.org/wiki/MIMD http://en.wikipedia.org/wiki/MIMD].&lt;br /&gt;
&lt;br /&gt;
* Wikipedia, Shared Memory Architecture [http://en.wikipedia.org/wiki/Shared_Memory_Architecture]&lt;br /&gt;
&lt;br /&gt;
* Wikipedia, SIMD [http://en.wikipedia.org/wiki/SIMD http://en.wikipedia.org/wiki/SIMD].&lt;br /&gt;
&lt;br /&gt;
* Wikipedia, SPMD [http://en.wikipedia.org/wiki/SPMD http://en.wikipedia.org/wiki/SPMD].&lt;br /&gt;
&lt;br /&gt;
* Wikipedia, Transputer http://en.wikipedia.org/wiki/Transputer&lt;br /&gt;
&lt;br /&gt;
* Wikipedia, Vector processor http://en.wikipedia.org/wiki/Vector_processor&lt;br /&gt;
&lt;br /&gt;
* Wikipedia, VMScluster http://en.wikipedia.org/wiki/VMScluster&lt;br /&gt;
&lt;br /&gt;
&amp;lt;!--&lt;br /&gt;
 // Data parallel implementation in C++ with OpenMP.&lt;br /&gt;
 &lt;br /&gt;
 #include &amp;lt;omp.h&amp;gt;&lt;br /&gt;
 #include &amp;lt;iostream&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 int main(void)&lt;br /&gt;
 {&lt;br /&gt;
     double a[8], b[8], c[8], localSum[2];&lt;br /&gt;
     long s = 4;&lt;br /&gt;
     int id, i;&lt;br /&gt;
 &lt;br /&gt;
     #pragma omp parallel for private(id, i) reduction(+:s)&lt;br /&gt;
     for (i = 0; i &amp;lt; 8; i++)&lt;br /&gt;
     {&lt;br /&gt;
         a[i] = b[i] + c[i];&lt;br /&gt;
     }&lt;br /&gt;
 &lt;br /&gt;
     for (i = 0; i &amp;lt; 2; i++) localSum[i] = 0;&lt;br /&gt;
 &lt;br /&gt;
     #pragma omp parallel for private(id, i) reduction(+:s)&lt;br /&gt;
     for (i = 0; i &amp;lt; 8; i++)&lt;br /&gt;
     {&lt;br /&gt;
         id = omp_get_thread_num();&lt;br /&gt;
         if (a[i] &amp;gt; 0)&lt;br /&gt;
             localSum[id] = localSum[id] + a[i];&lt;br /&gt;
     }&lt;br /&gt;
 &lt;br /&gt;
     double sum = localSum[0] + localSum[1];&lt;br /&gt;
     std::cout &amp;lt;&amp;lt; sum &amp;lt;&amp;lt; std::endl;&lt;br /&gt;
 }&lt;br /&gt;
--&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Appendix A: Example of Data Parallel with Other Code=&lt;br /&gt;
&lt;br /&gt;
Comparison of the data parallel section of code identified above with the sequential Code 2.3 of [[#References | Solihin (2008)]], which is reproduced below, supports the assertions of Hillis and Haveraaen mentioned above. The only differences between Codes 2.4 and 2.3 are the start and end indices and that, in the data parallel example, the variable sum is replaced by a private variable. Structurally the two codes are identical.&lt;br /&gt;
&lt;br /&gt;
 // Sequential code, from [[#References|Solihin (2008), p. 25.]]&lt;br /&gt;
 &lt;br /&gt;
 for (i = 0; i &amp;lt; 8; i++)&lt;br /&gt;
     a[i] = b[i] + c[i];&lt;br /&gt;
 sum = 0;&lt;br /&gt;
 for (i = 0; i &amp;lt; 8; i++)&lt;br /&gt;
     if (a[i] &amp;gt; 0)&lt;br /&gt;
         sum = sum + a[i];&lt;br /&gt;
 Print sum;&lt;br /&gt;
&lt;br /&gt;
=Appendix B: Data Parallel Versus Task-parallel=&lt;br /&gt;
&lt;br /&gt;
The logical opposite of data parallel is [[#Definitions | ''task parallel,'']] in which a number of distinct tasks operate on common data.  An example of a task parallel code which is functionally equivalent to the sequential and data parallel codes given above follows below for code 2.3 of [[#References | Solihin (2008)]] which was above written in data parallel format.&lt;br /&gt;
&lt;br /&gt;
 // Task parallel code.&lt;br /&gt;
 &lt;br /&gt;
 int id = getmyid(); // assume id = 0 for thread 0, id = 1 for thread 1&lt;br /&gt;
 &lt;br /&gt;
 if (id == 0)&lt;br /&gt;
 {&lt;br /&gt;
     for (i = 0; i &amp;lt; 8; i++)&lt;br /&gt;
     {&lt;br /&gt;
         a[i] = b[i] + c[i];&lt;br /&gt;
         send_msg(P1, a[i]);&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 else&lt;br /&gt;
 {&lt;br /&gt;
     sum = 0;&lt;br /&gt;
     for (i = 0; i &amp;lt; 8; i++)&lt;br /&gt;
     {&lt;br /&gt;
         recv_msg(P0, a[i]);&lt;br /&gt;
         if (a[i] &amp;gt; 0)&lt;br /&gt;
             sum = sum + a[i];&lt;br /&gt;
     }&lt;br /&gt;
     Print sum;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the code above, work is divided into two parallel tasks.  The first performs the element-wise addition of arrays ''b'' and ''c'' and stores the result in ''a.''  The other sums the elements of ''a.''  These tasks both operate on all elements of ''a'' (rather than on separate chunks), and the code executed by each thread is different (rather than identical).&lt;br /&gt;
&lt;br /&gt;
Since each parallel task is unique, a major limitation of task parallel algorithms is that the maximum degree of parallelism attainable is limited to the number of tasks that have been formulated.  This is in contrast to data parallel algorithms, which can be scaled easily to take advantage of an arbitrary number of processing elements.  In addition, unique tasks are likely to have significantly different run times, making it more challenging to balance load across processors.  [[#References | Haveraaen (2000)]] also notes that task parallel algorithms are inherently more complex, requiring a greater degree of communication and synchronization.  In the task parallel code above, after thread 0 computes an element of ''a'' it must send it to thread 1.  To support this, sends and receives occur every iteration of the two loops, resulting in a total of 8 messages being sent between the threads.  In contrast, the data parallel code sends only 2 messages, one at the beginning and one at the end.  The table below summarizes the key differences between data parallel and task parallel programming models.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;1&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
|+ '''Comparison between data parallel and task parallel programming models.'''&lt;br /&gt;
|-&lt;br /&gt;
! Aspects&lt;br /&gt;
! Data Parallel&lt;br /&gt;
! Task Parallel&lt;br /&gt;
|-&lt;br /&gt;
| Decomposition&lt;br /&gt;
| Partition data into subsets&lt;br /&gt;
| Partition program into subtasks&lt;br /&gt;
|-&lt;br /&gt;
| Parallel tasks&lt;br /&gt;
| Identical&lt;br /&gt;
| Unique&lt;br /&gt;
|-&lt;br /&gt;
| Degree of parallelism&lt;br /&gt;
| Scales easily&lt;br /&gt;
| Fixed&lt;br /&gt;
|-&lt;br /&gt;
| Load balancing&lt;br /&gt;
| Easier&lt;br /&gt;
| Harder&lt;br /&gt;
|-&lt;br /&gt;
| Communication overhead&lt;br /&gt;
| Lower&lt;br /&gt;
| Higher&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
One important feature of data parallel programming model or data parallelism (SIMD) is the single control flow: there is only one control processor that directs the activities of all the processing elements. In stark contrast to this is task parallelism (MIMD: Multiple Instruction, Multiple Data): characterized by its multiple control flows, it allows the concurrent execution of multiple instruction streams, each manipulates its own data and services separate functions. Below is a contrast between the data parallelism and task parallelism models from wikipedia: [http://en.wikipedia.org/wiki/SIMD SIMD] and [http://en.wikipedia.org/wiki/MIMD MIMD]. In the following subsections we continue to compare and contrast different features of data parallel model and task-parallel model to help reader understand the unique characteristics of data parallel programming model.&lt;br /&gt;
[[Image:Smid.png|frame|center|425px|contrast between data parallelism and task parallelism]]&lt;br /&gt;
&lt;br /&gt;
== Synchronous vs Asynchronous ==&lt;br /&gt;
While the [http://en.wikipedia.org/wiki/Lockstep_(computing) lockstep] imposed by data parallelism on all data streams ensures synchronous computation (all PEs perform their tasks at the exact same pace), every processor in task parallelism performs its task at their own pace, which we call asynchronous computation. Thus, at a certain point of a task parallel program's execution, communication and synchronization primitives are needed to allow different instruction streams to coordinate their efforts, and that is where variable-sharing and message-passing come into play.&lt;br /&gt;
&lt;br /&gt;
== Determinism vs. Non-Determinism ==&lt;br /&gt;
Data parallelism's synchronous nature and task parallelism's asynchronism give rise to another pair of features that add to the difference between these two models: determinism versus non-determinism. Data parallelism is deterministic, i.e. computing with the same input will always yield the same result, since its synchronism ensures that issues like relative timing between PEs will not arise. In contrast, task parallelism's asynchronous updates of common data can give rise to non-determinism, i.e, the same input won't always yield the same computation result (the result of a computation will depend also on factors outside the program control, such as scheduling and timing of other PEs). Obviously, non-determinism makes it harder to write and maintain correct programs. This partially explains the advantage of data parallel programming model over data parallelism in terms of development effort (also discussed in section 4.2).&lt;br /&gt;
&lt;br /&gt;
=Appendix C: C for CUDA Example Code=&lt;br /&gt;
&lt;br /&gt;
The following code is a data parallel implementation of the sequential Code 2.3 from [[#References | Solihin (2008)]] using [http://www.nvidia.com/object/cuda_learn.html C for CUDA].  It is presented to give an impression of programming for a SIMD architecture, but a detailed discussion is beyond the scope of this supplement.  Ignoring memory allocation issues, the code is very similar to the data parallel example, Code 2.5 from [[#References | Solihin (2008)]], discussed earlier.  The main difference is the presence of a control thread that sends the parallel tasks to the CUDA device.&lt;br /&gt;
&lt;br /&gt;
 // Data parallel implementation of the example code using C for CUDA.&lt;br /&gt;
 &lt;br /&gt;
 #include &amp;lt;iostream&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
 __global__ void kernel(float* a, float* b, float* c, float* local_sum)&lt;br /&gt;
 {&lt;br /&gt;
     int id = threadIdx.x;&lt;br /&gt;
     int local_iter = 4;&lt;br /&gt;
     int start_iter = id * local_iter;&lt;br /&gt;
     int end_iter = start_iter + local_iter;&lt;br /&gt;
 &lt;br /&gt;
     // Begin data parallel section&lt;br /&gt;
 &lt;br /&gt;
     for (int i = start_iter; i &amp;lt; end_iter; i++)&lt;br /&gt;
         a[i] = b[i] + c[i];&lt;br /&gt;
     local_sum[id] = 0;&lt;br /&gt;
     for (int i = start_iter; i &amp;lt; end_iter; i++)&lt;br /&gt;
         if (a[i] &amp;gt; 0)&lt;br /&gt;
             local_sum[id] = local_sum[id] + a[i];&lt;br /&gt;
 &lt;br /&gt;
     // End data parallel section&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 int main()&lt;br /&gt;
 {&lt;br /&gt;
     float h_a[8], h_b[8], h_c[8], h_sum[2];&lt;br /&gt;
     float *d_a, *d_b, *d_c, *d_sum;&lt;br /&gt;
     float sum;&lt;br /&gt;
 &lt;br /&gt;
     size_t size = 8 * sizeof(float);&lt;br /&gt;
     size_t size2 = 2 * sizeof(float);&lt;br /&gt;
 &lt;br /&gt;
     cudaMalloc((void**)&amp;amp;d_a, size);&lt;br /&gt;
     cudaMalloc((void**)&amp;amp;d_b, size);&lt;br /&gt;
     cudaMalloc((void**)&amp;amp;d_c, size);&lt;br /&gt;
     cudaMalloc((void**)&amp;amp;d_local_sum, size2);&lt;br /&gt;
 &lt;br /&gt;
     cudaMemcpy(d_b, h_b, size, cudaMemcpyHostToDevice);&lt;br /&gt;
     cudaMemcpy(d_c, h_c, size, cudaMemcpyHostToDevice);&lt;br /&gt;
 &lt;br /&gt;
     kernel&amp;lt;&amp;lt;&amp;lt;1, 2&amp;gt;&amp;gt;&amp;gt;(d_a, d_b, d_c, d_sum);&lt;br /&gt;
 &lt;br /&gt;
     cudaMemcpy(h_a, d_a, size, cudaMemcpyDeviceToHost);&lt;br /&gt;
     cudaMemcpy(h_sum, d_sum, size2, cudaMemcpyDeviceToHost);&lt;br /&gt;
 &lt;br /&gt;
     sum = h_sum[0] + h_sum[1];&lt;br /&gt;
     std::cout &amp;lt;&amp;lt; sum;&lt;br /&gt;
 &lt;br /&gt;
     cudaFree(d_a);&lt;br /&gt;
     cudaFree(d_b);&lt;br /&gt;
     cudaFree(d_c);&lt;br /&gt;
     cudaFree(d_sum);&lt;br /&gt;
 }&lt;/div&gt;</summary>
		<author><name>Dmcarmon</name></author>
	</entry>
</feed>