Question

I've just started learning Functional Programming (Scheme). But I still have problems thinking "functionally".

Something like:

func1(int a){
   if(a==100)
      a=0;
   return func2(a);
}

There's a state change there, so that's imperative programming.

If I take the "if" part and throw it into another function, does that make it funcional?

func1(int a){
   return func2(func3(a));
}

Is this what all's about?

Thanks!

Was it helpful?

Solution

Not really. First, there's several different definitions of what functional programming means, and it changes by community. Haskellers have a bit different idea of it than Schemers, usually.

Strictly speaking, functional programming uses functions as primitives, so that they can be put into variables and passed around as arguments, without them being evaluated in the process.

Haskellers will usually tack on the purity requirement. Functional purity is the idea that functions mustn't have side effects (including changes to state); i.e. each call to the function with the same arguments must return the same value.

Your second function fails on the first condition, the necessary one. You are not using functions as first-class citizens.

If you write it like this,

func1(int a) {
  return (
    if (a==100)
      then func(0);
      else func2(a);
    )
}

This is now pure, but it is neither particularly functional nor particularly imperative.

I can't really translate your example into something specifically functional, since there's too little context. The usual "hello world" for functional code is this:

square(x) = x * x
twice(f, x) = f(f(x))
twice(square, 4)
  => 256

Here we define a function square that multiplies the number by itself. We define another function twice that takes a function and an argument, and applies the function to the argument twice. Then we give the function twice the arguments square and 4. Note that this isn't twice(square(4)) - the function square is not evaluated until within the definition of the function twice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top