Ramda Functional Programming PHP

Source: Internet
Author: User
Tags parse error

0x00 What is functional programming

Online has been a lot of detailed acceptance, I think the more important are:

    1. Functions are "first class citizens", which are equal in function and other data types
    2. Use "expression" (refers to a simple operation procedure, always has a return value), rather than "statement" (Take action, no return value)
    3. No "side effects", that is, no external values are modified
0X01 begins functional programming

Prior to this, please understand the anonymous functions and closures in PHP, you can refer to the blog I wrote
Functional programming has two of the most basic operations: compositing and Curry.

function synthesis

function synthesis, that is, the operation of multiple functions to synthesize a function, such as
A=f (x)
B=g (x)
C=f (g (x))
Then C is the synthesis of A and B.
Expressed in code as:

$compose=function ($f,$g){return function ($x)  Use($f,$g){//Returns a function function, that is, the higher-order function        return $f($g($x));};};functionAddten($a){return $a+10;}functionSubone($a){return $a-1;}$z=$compose(' Addten ',' Subone ');//If you use the form of $addOne = function () {}, you can pass the variable directlyEcho $z(5);//

The function required to synthesize is also a pure function, if not pure function, then the result is inconsistent, how to synthesize it?
Compose returns a higher-order function that, when passed to the function of the composition, changes back to the function that was saved before the higher-order function was called.

Currying

You can see that if there is more than one function parameter passed in here, the composition function above will be invalidated.
This is the other big God that we need to use in another functional programming, Gerty. The so-called "curry" is to convert a multi-parameter function into a single-parameter function ".

//Before CurryfunctionAdd($a,$b){return $a+$b;}add(1, 2); //3//After curryingfunctionAddx($b){return function ($a)  Use($b){return $a+$b;};}$addTwo= Addx(2);$addTwo(1);//3

PHP7 The following direct call ADDX (2) (1), will be error , so the above used the intermediate variable $addtwo.

Parse error:syntax Error, unexpected ' ('

The consistent variable syntax is perfected above PHP7, and the PHP7 is faster, and it is highly recommended to use PHP7.

General currying , the curry is very good, but we can not write for each function once, then there is no wrapper function, you could change the ordinary function for the function of the curry?
The code is as follows: (Excerpt from: PRAMDA)

functionCurry2($callable){return function ()  Use ($callable){$args=Func_get_args();        Switch (Func_num_args()){ Case0:                Throw New\Exception("Invalid Number of arguments");                 Break;             Case1:                return function ($b)  Use ($args, $callable){return Call_user_func_array($callable, [$args[0], $b]);};                 Break;             Case2:                return Call_user_func_array($callable, $args);                 Break;            Default:                //Why? To support passing curried functions as parameters to functions this pass more then 2 parameters, like reduce                return Call_user_func_array($callable, [$args[0], $args[1]]);                 Break;}    };}functionAdd($a,$b){return $a+$b;}$addCurry= Curry2(' Add ');$addTwo=$addCurry(2);$addTwo(1);//3

Description, Curry2 returns a closure (such as the above $addcurry), and when the closure is called, it gets parameters dynamically through Func_get_args,
And Func_num_args dynamically get the number of parameters. Curry2 function as its name, you can give the number of parameters to two functions of the curry. So in the closures, we see,
In determining the number of arguments, when the number of arguments is 1 o'clock, a new closure is generated (as in the above $addtwo), the new closure holds the original function and the entire parameter,
When the new closure is called, Call_user_func_array is called to pass in the original function, the saved arguments, and the new parameters, obtaining the desired result.

Extension, functional programming there is another important concept, functor (that is, a class with a map method), more content can see the two articles of teacher Ruan, I will be unknown.

    • On functional programming
    • Functional programming Getting Started tutorial

Normally we use our own functions, if the idea of functional programming, can also be curry. Of course for more parameters the function has to use higher-order Curryn to curry.
These already have artificial good wheels, the following began to get to the point.

0x02 Ramda

This ramda is actually a pointfree style in functional programming.
In Ramda, the data is placed in the last parameter, the idea is "function First,data".
Like what

//Example 1functionMap(){$args=Func_get_args();    $n=Func_num_args();    $callable=$args[$n-1];    unset($args[$n-1]);    $res=[];    foreach ($args  as $v){if(Is_array($v)){foreach ($v  as $i){$res[]=Call_user_func($callable,$i);}        }Else{$res[]=Call_user_func($callable,$v);}    }return $res;}map(1,2,' Square ');//1,4Map([1,2],' Square ');//1,4//Example 2functionSquare($v){return($v*$v);}Array_map("Square",[1,2]);  //1, 4

The above code, example 1 is not RAMDA style, and Example 2 is RAMDA style.

Since there are man-made good wheels, then we directly use it, the following please out the protagonist, PRAMDA,RAMDA-style PHP functional programming library.

Installation

Composer require KAPOLOS/PRAMDA

If it appears

[InvalidArgumentException]
Could not the Find package Kapolos/pramda.

You can add "Kapolos/pramda" to the Composer.json: "Dev-master"

Example:

$before=[1,2,3,4,5];$after=P:: Map(function($num){return $num*2;}, $before);P:: ToArray($after); //=> [2,4,6,8,10]$addOne=P:: Add(1);$divTen=P::d ivide(Ten); //10 is the divisor$FN 1=P:: Compose($addOne,$divTen); //compose from right to left$FN 2=P::p Ipe($addOne,$divTen);//pipe from left to rightEcho $FN 1(1); //11Echo "\ n";Echo $FN 2(1); //5

Deficiencies, PRAMDA does not support placeholders, and the curry function supports up to 3 parameters.
There are also two functional programming libraries, functional-php and dash unfortunately not ramda style.
As Miss Ruan has mentioned,

Learning functional programming is actually a study of the various operations of a functor.

If you want to know more, you can continue to read the two articles of teacher Ruan.

    • Ramda Function Library Reference Tutorial
    • Pointfree Programming Style Guide

Ramda Functional Programming PHP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.