Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › functional programming
New Posts  All Forums:Forum Nav:

functional programming - Page 2

post #11 of 13
Thread Starter 
Quote:
Originally Posted by {Unregistered} View Post

Great. Sorry for the confusion.

Basically, in functional code, you write the code as an expression that you want the computer to return, without caring how exactly the computer deals with it. The easiest way to describe is using an analogy of functional recursion. Functional languages (which are declarative) don't allow a sequence of instructions or standard while/for loops, and therefore, must rely on recursion. So, for example, if you're writing a number that finds the factorial of a number n, you wouldn't use a for loop with a counter that goes from 0 to n, but the standard recursion algorithm. So, essentially, your whole mindset should change when you switch to functional programming from imperative programming. You don't want to tell the computer how to do something, but what to return, in terms of the data you have.
Further points might be that, pure functional languages don't modify data or variables once they're set, and don't cause any external side effects. Also, since the whole code is basically just a set of functions, the code is much more re-usable and adaptable, allowing for libraries of pre-defined functions to be included with a language specification, making it higher level, in a sense.

In general, functional code is much more concise and easier to read than imperative code, and therefore, allows for spending less time coding, but more time thinking about a solution.

So, even though, the idea of functional programming might not be very hard to grasp, actually changing your mind to think in a completely different way is much harder.

Thanks for that :-)

Sounds like I make use of most of those points already (not exclusively, but I do tend to lean towards that coding style). The first point sounds challenging though. How would you call functions in such a way that you emulate (for want a better term) recursion?
post #12 of 13
Quote:
Originally Posted by Plan9 View Post

Thanks for that :-)

Sounds like I make use of most of those points already (not exclusively, but I do tend to lean towards that coding style). The first point sounds challenging though. How would you call functions in such a way that you emulate (for want a better term) recursion?

I'm not quite sure what you mean. What I meant was, that unlike imperative code, functional code doesn't follow a control flow of a sequence of instructions, and therefore, doesn't have while and for loops, or multiple lines of code containing instructions that are to be carried out in sequence.

I'm not sure if I have anything to properly demonstrate this, but have a look at this code. It's in Haskell.
Code:
sumAllDigits :: [ Int ] -> Int
-- Sums the digits of each of the numbers in the list input.
sumAllDigits [] = 0
sumAllDigits (x : xs) = sumDigits x + sumAllDigits xs

I doubt this code shows anything you don't already know, as it's just standard recursion. What you should know is that according to this code, we don't care how to find the sum of all the digits of integer values in a list. All we know, is that sum of the digits of a list of integers is a sum of the digits of the first integer, plus the sum of the digits of the remaining integers. And that the sum of the digits of the integers in an empty list, is zero.
Please do tell me if I have misunderstood you.
MacBook Pro 13"
(6 items)
 
 
Desktop
(13 items)
 
CPUGraphicsRAMHard Drive
Intel i5 3210 @ 2.5 GHz Intel HD4000 4 GB DDR3 @ 1600 MHz 500 GB @ 5400 RPM 
OSMonitor
OSX Mountain Lion 13.3" @ 1280 x 800 
CPUGraphicsRAMHard Drive
Intel i5 480m@2.67GHz AMD Radeon Mobility 5650 4GB DDR3 500GB 
OSMonitor
Windows 7 64bit HP 15.6" 1366x768 
CPUMotherboardGraphicsRAM
E7500 Intel...:( MSI GTS250 1GB 2GB 
Hard DriveOSMonitorPower
250GB Windows XP 17" LG CRT 1280x768@85hz 400W 
  hide details  
Reply
MacBook Pro 13"
(6 items)
 
 
Desktop
(13 items)
 
CPUGraphicsRAMHard Drive
Intel i5 3210 @ 2.5 GHz Intel HD4000 4 GB DDR3 @ 1600 MHz 500 GB @ 5400 RPM 
OSMonitor
OSX Mountain Lion 13.3" @ 1280 x 800 
CPUGraphicsRAMHard Drive
Intel i5 480m@2.67GHz AMD Radeon Mobility 5650 4GB DDR3 500GB 
OSMonitor
Windows 7 64bit HP 15.6" 1366x768 
CPUMotherboardGraphicsRAM
E7500 Intel...:( MSI GTS250 1GB 2GB 
Hard DriveOSMonitorPower
250GB Windows XP 17" LG CRT 1280x768@85hz 400W 
  hide details  
Reply
post #13 of 13
Quote:
Originally Posted by Plan9 View Post


Interesting stuff. Are you able to expand on what the difference is between block scoping and lexical scoping because after a bit of Googling (ok, just Wikipedia redface.gif ) the results that come up say that ALGOL based languages (eg Pascal) and C all use lexical scoping - yet they're the very definition of imperative languages. Now I'm not trying to dispute your comparison as I'm not familiar with those terms and it's pretty obvious that you understand these concepts (and particularly functional programming) a great deal better than I. But I am rather confused now. frown.gif

I just hit the backspace on my keyboard (changing pages) and nerfed my megapost, so the retype is going to be brief.

 

//in C:

int Global;

{

  int outerBlock;

    {

       int innerBlock;

         {

           int inner_innerBlock;

         }

    }

}

 

//so for example

main(){

  int i=1;

  for(int i=5; i<10; i+=1){

     pass;

  }

}

//the int i inside the for loop is completely different from the int

//in the main function.

 

//now in JS

var Global; //due to JS design, globals are beyond evil

            //(far worse than most other languages)

var main = function(){ //assigns an anonymous function to the variable main

  var i = 1; //creates a variable

             //note: JS creates all variables in a particular scope upon

             //the scope's initialization, so declaring vars just before use

             //is considered bad form

  for(var i = 1; i<10; i+=1){

     //this is why it's bad form

     //it appears to create a new variable

     //but because for isn't a function this "new" var

     //is actually trying to initialize the same var i seen above

     //and since all variable initialization occurs on function initialization

     //C programmers get a mysterious error because they think

     //it's a different scope and thus a different variable

     //this is what I mean that looking like C doesn't mean that's

     //how the language actually works

  }  //end for

 

 (function(){ //this anonymous function inside main causes a new scope

    var inner = 5; //this var is actually different from the one in main

 }());         //I know this looks weird. Due to a syntax wart, JS

               //requires the () at the end of the anonymous function

               //in order to execute the function, but the outer

               //parenthesis are required to force it to execute

               //without them, it would expect a variable or function name

               //Another non-apparent trip up for C programmers who think

               //it acts the same because it looks the same

   console.log(i); //since there isn't an i, this looks at the next outer

                   //function to see if i exists, it returns an error if it

                   //gets all the way to global and still doesn't find variable i

}; //end function needs a semicolon as it is an assignment of a lambda func

   //to a variable

 

 

 

It's this function scoping that allows closures to work the way that the do. For example

 

var custom_add = function(x){//note that x is now a variable in the outer anon func

 

  var inner_func = function(y){ //this has access to x since this scope

                                     //is inside that scope

      return (x + y);                //we haven't defined y yet, but I'll get to it

  } //end inner func

 

  return inner_func; //this is where functional programming is in full swing

}; //end custom_add (the outer function)

 

An explanation of the previous is in order. Let's step through this in order of execution.

1. call the outer function (eg. myvar = custom_add(5); )

2. custom_add creates a variable x and gives it the value of 5

3. custom_add creates a variable inner_func and gives it the value of the anonymous function

4. custom_add returns the variable inner_func

 

I'll continue in a moment but first an explanation is in order. At this point, that instance of custom_add has ceased to exist. It has returned to the code that called it. The magic here is that inner_func still exists. Because it exists, the scope inside custom_add exists (even though custom_add no longer does). As long as there is a pointer that links to either of the variable that custom_add contained (x or inner_func) they won't be garbage collected. In this case, the variable myvar contains a link to the anonymous function linked to by inner_func, so the scope continues to exist until myvar is destroyed or given another value (in JS, variable are actually pointers to values and those values can be functions).

 

5. we now have myvar = inner_func = function(y){ return (x + y)} // where x in the scope was set to 5 when the outer function was called.

6. Now if we call myvar(8); it's the same as calling the anonymous function as:

function(var y = 8){ 

  var x = 5;

  return (x + y);

}

7. As you would expect, that returns 13.

 

Now if we do something like:

var add4 = custom_add(4);

var add5 = custom_add(5);

var add6 = custom_add(6);

var add7 = custom_add(7);

 

we have just effectively created 4 new functions that do different things. For example if we call all of these with 3:

add4(3); //returns 7

add5(3); //returns 8

add6(3); //returns 9

add7(3); //returns 10

 

Unfortunately, even this fairly simple case isn't anywhere near as easy in a language such as C. Here's another basic closure example using getter and setter methods.

 

var item = function(val){

  value = val; //note: this refers to the current scope

   

  this.get_value = function(){

    return value;

  };

   

  this.set_value = function (val){

    value = val;

  };

}

 

Once again to explain.

var my_instance = new item("string"); //the value and type doesn't matter for this example

the above calls the anonymous function and passes "string" as the value for val and makes a new copy of the item and a closure is created. Notice that you can't access value directly. Instead, you must interact with my_instance.get_value or my_instance.set_value because only these can interact with value as it is within the scope of this instance of item (note that item has already returned at this point despite JS not requiring an explicit return statement).

 

EDIT:

I forgot to add to my post (for the second write) that I misspoke about lexical scoping vs block scoping. I actually meant functional scoping vs block scoping. The alternative to lexical scoping is dynamic scoping. 

  


Edited by hajile - 5/30/13 at 5:58am
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Coding and Programming
Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › functional programming