How can you do anything useful without mutable state?

后端 未结 18 1753
栀梦
栀梦 2020-11-28 17:12

I\'ve been reading a lot of stuff about functional programming lately, and I can understand most of it, but the one thing I just can\'t wrap my head around is stateless codi

18条回答
  •  离开以前
    2020-11-28 17:59

    This is very simple. You can use as many variables as you want in functional programming...but only if they're local variables (contained inside functions). So just wrap your code in functions, pass values back and forth among those functions (as passed parameters and returned values)...and that's all there is to it!

    Here's an example:

    function ReadDataFromKeyboard() {
        $input_values = $_POST[];
        return $input_values;
    }
    function ProcessInformation($input_values) {
        if ($input_values['a'] > 10)
            return ($input_values['a'] + $input_values['b'] + 3);
        else if ($input_values['a'] > 5)
            return ($input_values['b'] * 3);
        else
            return ($input_values['b'] - $input_values['a'] - 7);
    }
    function DisplayToPage($data) {
        print "Based your input, the answer is: ";
        print $data;
        print "\n";
    }
    
    /* begin: */
    DisplayToPage (
        ProcessInformation (
            GetDataFromKeyboard()
        )
    );
    

提交回复
热议问题