Archive for the 'Lambda calculus' Category

Simple Functional Sniffer & Switch Alternative

mix Because PHP is a server-side language, you will have times that you need to rely on client-side languages like CSS, JavaScript and even HTML5 to accomplish certain tasks. In developing the CMS, I realized that while incorporating JavaScript, CSS and HTML5 in heredoc strings, I’d established a barrier between PHP and everything else by only allowing these other languages to interact with PHP through objects. Of course, this is because PHP has emerged into an OOP language and the others have not.

What I failed to take into account is the fact that it’s perfectly possible for OOP structures to interact with non-OOP structures. To some extend that has been done with HTML/CSS UIs and PHP design patterns in several examples. That seems to work out fine, but where you want to use dynamic variables for more responsive HTML pages, we’re back to encapsulating HTML (along with Javascript and CSS) into heredoc strings in PHP. There’s nothing wrong with that, and there’s much to be said for having a fully integrated OOP design pattern with a pure PHP engine.

A Simple Functional JavaScript Sniffer

The problem I discovered in a pure PHP design is that other design possibilities are overlooked. The primary style tool for HTML documents is CSS, and the media queries in CSS3 are designed to be responsive to different devices—namely, those brought about by mobile computing. Sometimes (and I do mean sometimes) that solution seems to work fine. Other, times, however, the media queries fail to capture that chunk of CSS3 code that formats for the desired device. On top of that, it can be difficult calling up certain jQuery mobile files—or any other files—from CSS alone. In many ways, libraries in jQuery have proven to be far more robust than CSS3 alone and far easier to deal with. In several respects, probably in most, neither CSS nor jQuery mobile are programming so much as they are styling tools. As such, they’re the tail of the programming dog. This is not to say they’re less important; they’re just not programming.

So, to sort out the devices looking at our pages, (moving away from CSS media queries) is a programming task. In several other entries on this blog, I’ve looked at ways to sniff through the possible devices, and I think we need to conclude once and for all that user-agents are next to useless. So, by exclusion, we’re left with screen width. So,begin by looking at this simple JavaScript sniffer using two lambda functions:

?View Code JAVASCRIPT
//Save as file name "jsniff.js"
var wide = screen.width;
var beta=function() {wide >=900 ? window.location.href="Desktop.html" :  window.location.href="Tablet.html";};
var lambda=function() {wide <= 480 ? window.location.href="Phone.html" : beta();};

In past posts I’ve used the Chain Of Responsibility (CoR) design pattern to do the same thing using either user agents (forget about it!) or width determined by a JavaScript object. The little JavaScript lambda functions do the same thing, and while at some point of granularity your may wish you had your CoR pattern, generally, I think that there’s enough with the three general categories at this point in time to deal with multiple device. Use the buttons to test the functions. (Try it with your phone and tablet too.) Click PlayA for the sniffer and PlayB for the PHP functional alternative to the switch statement. The download button downloads the source code for both.

PlayAPlayBDownload

The process is pretty simple both from a programming and a lambda calculus perspective. From lambda calculus we get following definitions of true and false:

true := λx.λy.x
false := λx.λy.y

As algorithms, we might consider the following:

function(x, y) {return x;};
function(x, y) {return y;};

So, that means:

function (10,20) = 10; ← true : Is 10
function (10,20) = 20; ← false : Not 10

That’s not exactly lambda calculus, but it’s along those lines that we can eke out an idea. (If you’re thinking, “What about function(10,10) that would appear to be both true and false,” you see what I mean.)

So now we’ll add the values a and b and reduce it:

((λx.λy.x) a b) -> ((λy.a) b) -> a

That replaces λx with (λy.a) b and then a. So a is a. Well, it sounds true!

Then for false we have:

((λx.λy.y) a b) -> ((λy.y) b) -> b

In looking at this, we see that if a is a its true; otherwise it’s b which is not true. That’s pretty much like if-then-else. If true a, otherwise it’s b.

So the line in JavaScript would be a ternary:

lambda = function(a) { return a ? a : b ;};

as well as in PHP,

$lambda = function($a) { return $a ? a : $b ;};

For now, that’s enough linking up lambda calculus with Internet languages. With our JS “sniffer” using a simple HTML call, we can get the page configuration we want for our device based on the window size:

<html>
	<head>
		<title>Functional Sniff</title>
			<script src="jsniff.js"></script>
	</head>
	<body onload=lambda()>
	</body>
</html>

Try it out. It’s easy to write and it’s practical. What’s more, you can see how close everything is to a Boolean type decision. (The different device HTML5 files are in the materials in the download package; one of which uses the jQuery Mobile formatting.)

I Don’t Need No Stinkin’ Switch Statement

One of the nice things about functional programming is that it made me re-think how I was programming. One of the areas where I thought I’d be able to boil down an algorithm to something more compact came when I decided to break down a calendar output into four weekly segment. Using a jQuery calendar, I could pick a day and pass the information to a PHP class for processing. Initially, the switch statement came to mind as a solution in something like the following:

$d=$this->numDay;
switch ($d)
       {
         case ($d >=1 && $d<=7):
            return "jquery";
            break;
        case ($d> 7 && $d<= 14):
            return "haskell";
            break;
        case ($d> 14 && $d<= 21):
            return "php";
            break;
        default: return "racket";
       }

In looking for a range, each case acts like a little function. So why not use lambda functions in PHP to do the same thing. Each query (case/function) either returns a value or goes on to the next case. Here’s what it looks like:

$gamma=function($d) {return $d > 14 && $d <= 21 ? "php" : "racket";};
$beta = function($d) use ($gamma) {return $d > 7 && $d <= 14 ? "haskell" : $gamma($d);};
$lambda = function($d) use ($beta) {return $d >=1 && $d <=7 ? "jquery": $beta($d);};
return $lambda($this->numDay);

The last used lambda function is the first in the list ($gamma). That’s because in order for the subsequent function to call them with the use statement, the function used must be defined before the one using it. In functional programming, the use of one function by another is referred to as a closure.

The Language Mix-Master

With the key parts in place, take a look at the different parts and languages used. First of all, the program begins with an HTML5 UI. It links to the jQuery UI JavaScript files and the CSS files. A further stylesheet links to the local CSS.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
   <link rel="stylesheet" href="lang.css">
  <script>
  $(function() {
    $( "#datepicker" ).datepicker();
  });
  </script>
</head>
<body>
  <h2>Language of the Week</h2>
  <h4>Click in the text box to select from pop-up calendar: </h4>
 <form action="LangWeek.php" method="post" name="useUI" target="showpix">
<p>Date: <input type="text" id="datepicker" name="pick" /></p>
<input type = "submit" value="Get Language" />
</form>
 <iframe name="showpix" width="300" height="300"></iframe>
</body>
</html>

A form links to a PHP file where it passes the selected datepicker() value. The iframe tag provides a visual feedback embedded in the HTML page. (Note: Remember, with HTML5, iframes are no longer evil.)

Finally, using a single PHP class, the selected date is reconfigured to an integer and evaluated by the lambda functions described above in lieu of a switch statement:

<?php
error_reporting(E_ALL | E_STRICT);
ini_set("display_errors", 1);
 
class LangWeek
{
    private $dateNow,$dayMonth, $numDay;
 
    public function __construct()
    {
        $this->dateNow = $_POST['pick'];
        $this->dayMonth=substr($this->dateNow, 3,2);    // Start 03  : 2Length
        $this->numDay = intval($this->dayMonth);
        echo "<img src='images/{$this->chooseLanguage()}' . '.jpg'>";
    }
 
    private function chooseLanguage()
    {
        $gamma=function($d) {return $d > 14 && $d <= 21 ? "php" : "racket";};
        $beta = function($d) use ($gamma) {return $d > 7 && $d <= 14 ? "haskell" : $gamma($d);};
        $lambda = function($d) use ($beta) {return $d >=1 && $d <=7 ? "jquery": $beta($d);};
        return $lambda($this->numDay);
    }   
}
$worker = new LangWeek();
?>

Fortunately the jQuery date picker passes the date as a consistent string mm/dd/yyyy, and so the only requirement is to use a substring to find the day of the month and convert it to an integer. This is passed to the chooseLanguage() method that employs the lambda functions.

Mixing it Up

While this blog is dedicated to PHP Design Patterns and their application, I believe that PHP programmers should explore beyond OOP and try out different kinds of programming within an OOP framework, which happily exists within a Design Pattern. The willingness to explore and experiment keeps programming fresh and interesting in any language.

Share

Sandlight CMS V: Functional Protective Proxy Login

loginOn this blog, the Protective Proxy pattern has several different implementations, and if you’d like to refresh your memory, this post has the foundation upon which the others are built. The design pattern for the Proxy is relatively simple: the user logs into a site, and instead of going directly to the subject page, users are sent to a Proxy subject where their credential are checked. If the Proxy page determines valid credentials (typically a username and password), the user is sent to the subject page where the content resides.

With an administrative login, the work to be done (in this case) is to add and edit dynamic content for a page. The upper right portion of the main page is made up of materials that come from a database so that adding and changing content is relatively simple. However, before even getting to the administrative editing portion of the CMS, you want to be sure that only those with permission have access to the dynamic editor. So this post deals only with the login portion of the CMS. Go ahead and test it and download the source files:
PlayDownload

Rats! I forgot to tell you the username and password. You can find them in the source code in the download or in this post; so go ahead and dig them up and try again. It will help you understand how this proxy implementation works.

The Functional Protective Proxy

As noted above, other examples of the Proxy design pattern have been used and explained elsewhere on this blog. In this (protective) Proxy implementation, only one feature has changed: the methods are all written using functional programming protocols. Figure 1 shows the design pattern diagram for this implementation of the Proxy.

Figure 1: Class diagram for Protective Proxy

Figure 1: Class diagram for Protective Proxy

As far as protective Proxys go, this one is not unusual. The ReLog could have been handled by sending the user back to the LoginUI, but by having a different looking UI, it helps the user pay attention a bit more prior to re-entering the username and password. The path it follows is pretty simple:

  1. LoginUI: User enters username and password.
  2. LoginClient: Sends login request to LoginProxy.
  3. ILogin: Sets up two abstract methods and a concrete method along with encoded usernames and passwords. It also provides several protected properties. Both the LoginProxy and Login classes implement (extend) this abstract class interface
  4. LoginProxy: Evaluates username and password and sends it to Login if correct and ReLog if not.
  5. Login: Calls AdminUI (to be developed).
  6. ReLog: Re-start process requesting user name and password.

You can obscure the password and username better than I did for this example of the Proxy implementation. When used in an actual environment, you can store the codes in a special MySql table, a Json file, a text file or even a hidden element in an HTML5 document. Since users are not going to be logging in, other than the site administrator, you should be sure that they cannot even find where to log in! It’s a lot easier than trying to protect a site where users are expected to login.

When you look at the different classes, you won’t see much functional programming except in LoginProxy class. That’s because, there’s not a lot of code in any of the classes. The UI (LoginUI and ReLog) classes create and display HTML pages, the client class calls the proxy class (LoginProxy) but it’s the LoginProxy that has to do all of the thinking. Using functional operations, primarily lambda functions (PHP anonymous functions), the class methods determines what to do next: send on the request to the Login object or reroute it to the start-over class, ReLog. That’s pretty much it. In looking at the LoginProxy class code, you can see the functional operations at work:

< ?php
class LoginProxy extends ILogin
{
	//Proxy Subject
	public function doLogin()
	{ 	
		$this->sun=$_GET['username'];
		unset($_GET['username']);
		$this->spw=$_GET['password'];
		unset($_GET['password']);
 
		try
		{
			$this->security=$this->setPass();
			$this->igor=$this->sun==base64_decode($this->security[0]) && $this->spw==base64_decode($this->security[1]);
			$lambda=function($x) {$alpha=$this->igor ? $this->passSecurity=true : NULL; return $alpha;};
			$lambda($this->igor);
			$this->loginOrDie();
		}
 
		catch(Exception $e)
		{
			echo "Here's what went wrong: " . $e->getMessage();
		}
	}
 
	protected function loginOrDie()
	{
		$badPass=function($x) {$delta= $x ? ($this->goodLog=new Login()) : ($this->badLog=new ReLog());};
		$badPass($this->passSecurity);
		$goodPass=function($x) {$tau= $x ? ($this->goodLog->doLogin()) : NULL;};
		$goodPass($this->passSecurity);
	}
}
?>

Using the two methods implemented from the ILogin interface (abstract class), doLogin() and loginOrDie(), the functions work to determine whether 1) the password and username are correct and 2) send the request to the correct object: Login or ReLog.

What functional programming seems to do, among other things, is to create a series of binary queries with Booleans. For example, the protected variable $igor ($this->igor) has a double boolean assigned to it whereby two (2) comparative statements must resolve to true. By doing so, $igor becomes a Boolean value. (Who’s the Boolean now?! Snap!) Next, $igor, is a Boolean, as an argument in a lambda function ($lambda) determines whether the $passSecurity variable is to be changed from false to true—yet another Boolean!

In the loginOrDie() method, the $passSecurity variable is used again—this time as an argument—in the the $badPass() and $goodPass() lambda functions. That’s how this implementation of the protective Proxy determines whether the password and username are valid. The same determination could have been done using imperative conditional statements (e.g., if, switch), but in moving towards more functional programming within design pattern structures, the functional statements accomplish the same task with non-imperative programming.

In looking at the Login class, what is referenced as the “Real Subject” in design patterns, it does little more than pass the request to a user interface where the actual administration work can be done.

< ?php
class Login extends ILogin
{
	//Real Subject
	public function doLogin()
	{ 
		$this->loginOrDie();
	}
 
	protected function loginOrDie()
	{
		$admin=new AdminUI();
		$admin->dataStrat();
	}
}
?>

A tighter implementation would have us place the UI for the Administration module in the Login itself, but we’re not striving for “tightness.” Rather, this code moves a loosely bound module in a Proxy pattern to the next module using a Strategy pattern. As you will see in the interface used by both the LoginProxy and Login classes, the Login class only implements the two abstract methods and uses none of the other other protected properties or method. Continue reading ‘Sandlight CMS V: Functional Protective Proxy Login’

Share

PHP Functional Programming Part III: λ Lambda Calculus

lambdaCalcλ After learning how to program in Haskell, a pure functional programming language, in the edX course offered through TU DelftX I’m convinced more than ever that to do decent functional programming, you need to understand lambda calculus. I’m not saying that you need to master lambda calculus, but you need to understand it insofar as it applies to functional programming and differentiates imperative programming (what we do in sequential, procedural and OOP with PHP, Java, JavaScript, C++, and C#) and functional programming based on lambda calculus. In this post, I’d like to ease into lambda calculus and illustrate how it applies to functional programming in PHP.

It’s Not Like Other Programming Languages

A typical value a programmer may want to generate for a business site is the cost of an item plus shipping charges. By way of example, suppose that the shipping charges are all 11% of the cost of the item. You might write something like the following:

$priceNship = 14.95 + (14.95 * .11);

That’s not especially useful since you need to have a separate set of literals for each item to enter into the variable $priceNship.

You’re most likely to set up a method that handles such calculations with a variable generated through an argument. For example, you might have a class that looks like the following class and method:

<?php
class RetailStore
{ 
    private $priceNship;
 
    public function addShipping($x)
    {
        $this->priceNship = $x + ($x * .11);
        return round($this->priceNship,2);
    }
}
$worker = new RetailStore();
echo "Cost plus shipping: $" .  $worker->addShipping(14.95);
?>

I used the $x identifier for the parameter for the addShipping() method instead of something more descriptive like $cost because you’ll often see an x-named variable in lambda calculus.

Casting in Lambda Calculus

When using lambda calculus, one of the key characteristics that I had problems getting used to in Haskell was what you might call stating a problem or abstracting a problem. The problem statement is an abstraction of the problem you want to solve using functional programming. Because lambda calculus strives for abstraction, we’ll start with a simple one:

λx.x + (.11 (x))

What does that mean? First of all λx denotes a lambda function. The x variable is bound to the λ function. (It’s known as a bound variable as opposed to free variables. This post deals with bound variables only.) Put into a PHP class and methods, and setting up a return routine, you have the following:

?php
class RetailStoreFunc
{    
    public function addShipping($x)
    {
        // λx.x + (.11 (x))
        $priceNship = function ($x) {return $x + ($x * .11);};
 
        //Round off to 2 decimal points and return
        return round($priceNship($x),2);
    }
}
$worker = new RetailStoreFunc();
echo "Cost plus shipping: $" . $worker->addShipping(14.95);
?>

The λ function (lambda function) shows that the x value is added to the result of .11 times the value of x. In PHP, a λ function is the same as an anonymous or unnamed function. Now, looking at the PHP version of the λ function, you can see:

λx.x + (.11 (x)) = function ($x) {$x + (.11 *$x);};

If you compare the λ calculus with the PHP function, you can see that while the PHP function is a bit less abstract than the λ calculus expression, they are almost identical. Think of the λ calculus as nothing more than an abstraction of a solution.

If you can understand these introductory elements of λ calculus as applied to PHP, not only are you on the path to understanding λ calculus but also PHP functional programming. It’s not as difficult or large as other calculi; so, rest easy and continue.

Functions within Functions

Not only can λ functions return calculated values, they can return other λ functions. So, if you build one λ function, you can use it in another λ function. In this way you can build functional programs. Further, I have not found any contradiction between λ functions and functional programming and OOP in PHP. This next example shows another example of a λ functions in an OOP context, but unlike the first one this one 1) incorporate and returns one λ function in another, and 2) uses a private variable. You cannot assign a λ function to a variable that is not local (part of the method), but you can assign a non-local variable (e.g., private, public or protected) to store the results of a λ function—just not the λ function itself.

<?php
class RetailStoreReady
{    
    private $final;
    public function addShipNtax($x)
    {
        // λx.x + (.11 (x))
        $priceNship = function ($x) {return $x + (.11 * $x);};
 
        // λx.λx + (.07 (x)) (λx. $priceNship(x) + .07 (x))
        $totalWithTax = function ($x) use ($priceNship) {return $priceNship($x) + (.07 * $x);};
 
        //Using an embedded property ($final) for storing results
        $this->final=round($totalWithTax($x),2);
        return $this->final;
    }
}
$worker = new RetailStoreReady();
echo "Cost plus shipping and tax: $" . $worker->addShipNtax(14.95);
?>

In PHP, employ the use statement when one or more λ functions are within a λ function. To employ more than a single λ function within another λ function, you can separate the λ functions by a comma in the use statement as the following shows:

function ($x) use ($lambdaA, $lambdaB) {return $lambdaA($x) + $lambdaB($x);};

The ability of PHP to incorporate these functional programming elements indicates the commitment the PHP community has to functional programming.

Do You Really Need λ Calculus to learn Functional Programming in PHP?

If you read Simon Holywell’s book Functional Programming in PHP, you will find mention of λ calculus, but only a mention. Indirectly, there are some examples, and I found that some basic understanding of λ calculus is very helpful. But λ calculus is not a requirement for functional programming in PHP or any other language. However, if you do understand something about λ calculus, it is extremely helpful to better grasp functional programming in virtually any programming language. In future posts on functional programming, I will be introducing more elements of λ calculus that pertain to better understanding and using functional programming in PHP.

Share