+1  A: 

Fizzbuzz

Erlang functional

fizzbuzz() ->
    F = fun(N) when N rem 15 == 0 -> "FizzBuzz";
           (N) when N rem 3 == 0  -> "Fizz";
           (N) when N rem 5 == 0  -> "Buzz";
           (N) -> integer_to_list(N)
        end,
    [F(N)++"\n" || N <- lists:seq(1,100)].

What makes this functional is there is no step by step instructions (procedure) to its execution. It is all functions that just operate on data and return a result, and pattern matching determines when it is complete based on the data that is input to the initial function, which in this case is the last statement in the code.

C procedural

#include<stdio.h>

int main (void)
{
    int i;
    for (i = 1; i <= 100; i++)
    {
        if (!(i % 15))
            printf ("FizzBuzz\n");
        else if (!(i % 3))
            printf ("Fizz\n");
        else if (!(i % 5))
            printf ("Buzz\n");
        else
            printf ("%d\n", i);
    }
    return 0;
}

What makes this procedural is that the steps are in a specific order and follow a fixed procedure, Starting with the first instruction. Each line executes one after the other with the declaration of int i and follow in the order they are declared in, the procedure inside the loop is a fixed set of steps that execute in the order they are declared in each time the loop iterates until the loop is done.

Procedural programming is more like following a set of fixed instructions with each instruction executed in the order they are declared in, starting with the first and ending with the last.

Functional programming is more of defining functions that do something and linking them all together where the outputs of one feed the inputs of the next function, the behavior is determined by the data on the initial input and not on the order the functions are declared in.

fuzzy lollipop
+5  A: 

Procedural and imperative progammings are orthogonal. Procedural programming is opposed to object-oriented programming usually. C# (that is object-oriented language with partial functional features) Imperative style:

int sum = 0;
for (int i = 0; i < 150; i++)
{
    if (i % 5 != 0)
      sum += i;
}

Functional style:

int sum = Enumerable.Range(0, 150).Where(i => i % 5 != 0).Sum();

In first case you program how to do, in second - what to do.

STO
+1  A: 

An imperative program emphasizes changes in state, whereas a functional program treats the computation at hand as an application of functions. Let's look at a simple example, the factorial. I'll write this example in java.

Imperative

int n = 10
int total = n
while (n > 0)
{
   n--;
   total = total * n;
}

vs Functional

int factorial(n,total)
{
  if(n==0)
     return total;
  else
     return factorial(n-1,total*n);
}
factorial(10,1);

The imperative programming approach reads like a scripting language, where each command is executed individually, or by a control structure. Th functional approach seeks to take code that is executed more than once and enable its re-use by putting it into a first-class object called a function.

Josiah
@Josiah, your functional is only recursive. That isn't functional programming.
Lucas B
@Lucas B recursion is the functional equivalent of looping in an imperative program. The difference is that rather than modifying a global variable (thus changing the "state" of the program) the functional code works on a value local to the function and then returns the value without modifying any variables external to the function.
Josiah
@Josiah Just because something is a "function" doesn't make it functional programming. In my understanding, you have to pass the function into the Method as a value(aka parameter) for this to be considered functional programming.
Lucas B
@Lucas: Functional programming is about more than just higher order functions. Favoring recursion and immutable variables over traditional loops with mutable variables, is certainly an important aspect of the functional paradigm.
sepp2k
+1  A: 

[ Copied from my own answer in other thread ]


Task: Write a program to index a list of keywords (like books).

Explanation:

  • Input: List<String>
  • Output: Map<Character, List<String>>
  • The key of map is 'A' to 'Z'
  • Each list in the map are sorted.

Imperative Solution in Java:

import java.util.*;

class Main {
  public static void main(String[] args) {
    List<String> keywords = Arrays.asList("Apple", "Ananas", "Mango", "Banana", "Beer"); 
    Map<Character, List<String>> result = new HashMap<Character, List<String>>(); 
    for(String k : keywords) {   
      char firstChar = k.charAt(0);     
      if(!result.containsKey(firstChar)) {     
        result.put(firstChar, new  ArrayList<String>());   
      }     
      result.get(firstChar).add(k); 
    } 
    for(List<String> list : result.values()) {   
      Collections.sort(list); 
    }
    System.out.println(result);         
  }
}

Functional Solution in Scala:

object Main {
  def main(args: Array[String]) {
    val keywords = List("Apple", "Ananas", "Mango", "Banana", "Beer")
    val result = keywords.groupBy(_(0)).mapValues(_.sorted)
    println(result)
  }
}
missingfaktor
+1  A: 

[ From Stuart Halloway's Clojure Presentations ]


Task: To check whether a given string is blank.

Imperative Java Solution:

public static boolean isBlank(String str) {
  int strLen;
  if(str == null || (strLen = str.length()) == 0) {
    return true;
  }
  for(int i = 0; i < strLen; i++) {
    if((Character.isWhitespace(str.charAt(i)) == false)) {
      return false;
    }
  }
  return true;
}

Functional Clojure Solution:

(defn blank? [s]
   (every? #(Character/isWhitespace %) s))

Functional Scala Solution:

defn isBlank(s: String) = s.forall(_.isWhitespace)
missingfaktor