Welcome Guest, Not a member yet? Register   Sign In
Functional PHP Extension
#1

[eluser]Jamongkad[/eluser]
Functional PHP Extension

I all it's been a while since my last contribution to this community. But I feel that CI has given us so much in terms of developer happiness. It actually made me appreciate PHP again. Anyways here again is my small contribution to the community.

Just a few months ago I started to appreciate the power and expressiveness of Functional Programming, my work in using languages such as Scheme has opened my mind to new paradigms. I wanted to know if languages such as PHP can atleast scratch the surface of the power of FP.

Unfortunately in order to do anything remotely related to FP the language must support higer order functions(functions as first class citizens) which PHP does not. Lexical Scoping(which PHP does not execute as elegantly as other languages). These and a lot more are required, thus we come to the this humble library. Please note this library is more of a supplement and a helper to your code. I know it helped me a whole and I hope it does the same for you.

I'm currently the maintainer and active contributor to this library and I would like to share with the community the possiblity of writing code in a more functional manner and practicing Paul Graham's theory on power

So without further ado I'm pretty amped to demonstrate the power of this library with a few examples.
In order to load this library one must simple place it in their helpers folder. Change the file name to functional_helper.php and simply autoload it.

Anonymous Functions
The main crux of this library and the reason why I use it. One would want to utilize the power of unnamed functions for tasks that do not generally require the use of named functions. Small throw away tasks that one can utilize.

In order to invoke the use of anonymous functions...now I know some of you might be thinking that PHP has create_function. And I'm here to tell you that in the true spirit of FP anonymous functions immediately return their expressions. Create_function in all it's awkwardness defines it's expressions procedurally.

Here I define two lamdba functions.
Code:
$plus5 = lam('$x','$x + 5');
$times2 = lam('$x','$x * 2');

$combine = $plus5($times2(7));
//the result will be 19
Awesome isn't it? The library is well commented and you can find more examples I cooked up.

Scheme like Begin
This function was borrowed from Scheme and it allows the one to invoke functions by sequence. The function was inspired by the work of Dikini.net and his contributions.

Code:
function say() {
   echo "My";
}

function my() {
   echo " name ";
}

function name() {
   echo " is Mathew Wong.";
}

echo begin(
        say(),
        my(),
        name()
      );

//which would yield "My name is Mathew Wong."

Concat is the missing array reduction operation in PHP. It's closely related to implode.
Code:
$arr = array(
         'My name is Mathew Wong',
         'Ian Kjos is the original author of the Functional PHP library',
         'This is his implementation',
         'I love Functional programming!'
        );
echo concat($arr,'<br/>');
//Which will result....
    My name is Mathew Wong
    Ian Kjos is the original author of the Functional PHP library
    This is his.....
    I love Functional....

These trivial examples obviously do not do the library and it's original author justice. But for the sake of brevity I wanted to show you guys a taste of the expressive power that is contained in this library. There are alot more functions and combinators in the library that if I were to list them all one page would not be enough for this post.

Thank you and if there any questions I'll be more than happy to entertain them.
#2

[eluser]sophistry[/eluser]
wow. those links are really deep. i've brushed up against FP for a few years now and am interested in exploring this point of view.

for the benefit of the CI community would you supply a tidy "real world" example of how you are using functional programming in your CI project.

thx.
#3

[eluser]xwero[/eluser]
I second sophistrys' request for a real world example. For instance the Scheme like Begin example could be written like
Code:
say().my().name();
As the functions echo their content. Even if you use return in the function, which is recommended you can do
Code:
echo say().my().name();
#4

[eluser]m4rw3r[/eluser]
This seems cool, but what is wrong with implode('&lt;br /&gt;',$arr); ?
BTW, how good is the performance when using one of those anonymous functions?

And with echo, you can do this:
Code:
echo say(), my(), name();
#5

[eluser]Jamongkad[/eluser]
Certainly I'm sorry I just knew I should have used a more concrete example of the library. But here we go! I have to admit that the most used construct in the library is the lambda function "lam()". So I guess I'll use that first and build up from there shall we?

For instance I want to highlight a few things in my models. We're assuming I have already autoloaded the library.
Code:
class SampleModel extends Model{
   function __construct() {
    parent::__construct();
   }

   function fetch_dates() {
    $query = $this->db->get('table');

    //for string concatenation...
    $display = null;
    foreach($query->result() as $rows):
      //Ok with out going into to much detail this example anonymous function below checks a date object from the DB.
      //It checks if the date is today then display (New Project) beside it.
      $highlight_date = lam('$x','$x === date("Y-m-d")) ? "(New Project)" : null');
      $display .= $highlight_date($rows->date_from_db);
    endforeach;

    return $display;
   }
}

I would post more examples tomorrow as I'm feeling a bit under the weather.
#6

[eluser]Sam Dark[/eluser]
You need more docs and examples. The idea itself is good but it need to be explained.
#7

[eluser]Pascal Kriete[/eluser]
This is brilliant. It's definitely on my (rather lengthy) todo list.
#8

[eluser]Jamongkad[/eluser]
[quote author="Sam Dark" date="1215433250"]You need more docs and examples. The idea itself is good but it need to be explained.[/quote]

You're right unfortunately I'm trying to find time to make the documentation for the library. Pretty busy in work these days.
#9

[eluser]Jamongkad[/eluser]
[quote author="inparo" date="1215434656"]This is brilliant. It's definitely on my (rather lengthy) todo list.[/quote]

You're welcome! I hope to post so more examples and uses of the library. I'm just not feeling well as of today.
#10

[eluser]sophistry[/eluser]
@Jamongkad - thanks for the new sample code. however, i am having a hard time understanding the benefits of adopting this coding paradigm.

the revised example you offer above shows the lambda function defining a new function that is essentially a (less functional, less clear) display output function like this:
Code:
function label_new_if_today($date, $date_format="Y-m-d", $label="(New Project)")
{
    return ($date === date($date_format)) ? $label : null;
}

being the developer of the FP library for PHP, i'm sure you are familiar with many of these arguments... but i'll lay out a few anyhow.

first of all, this function has a name - it should be clear to everyone who reads it. the string in the lam() function has to be studied to understand what it does.
second, it has parameters with defaults that are spelled out - what if i wanted to abstract that lam() function so that it could do a string compare on a different date format?
third, this function will be recorded in function_exists().

other issues...
there are many problems when you embed PHP code in a string - the most important immediate effect is that you lose the syntax.
you also lose the ability to reuse your function in another scope. the function is also hidden inside code.

in this case, defining a real function is better overall - i don't think you could convince anyone to adopt lambda functions to allow inline function creation based on string output function.

it seems to me that there must be a more compelling example for adopting FP than string output and concatenation...
maybe something that dramatically shifts the coding architecture?
some better way of working in teams, splitting up large problems?
making unit testing easier?
maybe there is a particular problem domain where FP is better suited? maybe an event-driven system?

sorry to be a pest, but you seem like a smart coder and i'd like to know what you are thinking.




Theme © iAndrew 2016 - Forum software by © MyBB