doulu1867 2017-10-08 20:05
浏览 39
已采纳

php functional-php library less_than函数

I saw in source code of php-functional library such function :

function less_than($b)
{
    return function ($a ) use ($b) {
        return $a < $b;
    };
}

I can't get there $a comes from. How is this going to work?

We pass only $b to function less than and $a is undefined.

This is the link to source code where I took it from.

  • 写回答

1条回答 默认 最新

  • dpj0015 2017-10-08 20:10
    关注

    The idea of functional programming is that functions are first-class objects. So you can pass functions as parameters; and you can return functions.

    So here you can construct a function:

    $func_less = less_than(3);
    

    So we basically construct a function like:

    $func_less = function ($a) {
        return $a < 3;
    };
    

    and now $func_less is a function that takes a parameter $a and checks if that $a is less than three. For example:

    php > $func_less_three = less_than(3);
    php > var_dump($func_less_three(2));
    bool(true)
    php > var_dump($func_less_three(14));
    bool(false)
    

    So first we construct a function $func_less_three, then we call that function with two numbers 2 and 14. Since 2 is less than 3, it returns bool(true) on the first call, and since 14 is not less than 3, it return bool(false) on the second call.

    In most functional programming languages like Haskell, all functions take exactly one parameter. So instead of adding two numbers together, one first constructs a function that adds a (in that function) constant value to a parameter.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?