R
R
Rishat Sultanov2017-04-14 10:52:41
PHP
Rishat Sultanov, 2017-04-14 10:52:41

How to reverse a treeview list recursively?

Good afternoon, gentlemen :)
In general, I’m trying to delve into data abstraction now .. My head is spinning, theoretically I catch it, but in practice I’m immediately stunned :(
How did you delve into data abstraction? Have you solved small problems? Or did you have to understand this in practice?
Here For example:

['(((4, 5), 6), 5, (2, 3), 1)', l(1, l(3, 2), 5, l(6, l(5, 4)))]

There is a treeview, how can I reverse it? Not using ready-made functions.
In my case, tests are written for this.
<?php

namespace App\Solution;

require 'Pair.php';

use function App\Pair\car;
use function App\Pair\isPair;
use function App\Pair\cdr;
use function App\Pair\cons;
use function App\Pair\listToString;

function reverse($list)
{
    // BEGIN (write your solution here)

    // END
}

<?php

namespace App;

require_once 'Solution.php';

use function App\Pair\l;
use function App\Pair\listToString;

class TestSolution extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider additionProvider
     */
    public function testReverse($expected, $source)
    {
        $this->assertEquals($expected, listToString(Solution\reverse($source)));
    }

    public function additionProvider()
    {
        return [
            ['(((4, 5), 6), 5, (2, 3), 1)', l(1, l(3, 2), 5, l(6, l(5, 4)))],
            ['(((7), 6, 5, (100, 4), 3))', l(l(3, l(4, 100), 5, 6, l(7)))]
        ];
    }
}

There are functions
<?php

namespace App\Pair;

function cons($x, $y)
{
    return function ($method) use ($x, $y) {
        switch ($method) {
            case "car":
                return $x;
            case "cdr":
                return $y;
        }
    };
}

function car(callable $pair)
{
    return $pair("car");
}

function cdr(callable $pair)
{
    return $pair("cdr");
}

function listToString($list)
{
    if (!isPair($list)) {
        return $list;
    }

    $arr = [];
    $iter = function ($items) use (&$arr, &$iter) {
        if ($items != null) {
            $arr[] = listToString(car($items));
            $iter(cdr($items));
        }

    };
    $iter($list);

    return "(" . implode(", ", $arr) . ")";
}

function l()
{
    return array_reduce(array_reverse(func_get_args()), function ($acc, $item) {
        return cons($item, $acc);
    });
}

function accumulate($list, $func, $acc)
{
    $iter = function ($list, $acc) use (&$iter, $func) {
        if ($list === null) {
            return $acc;
        }

        return $iter(cdr($list), $func(car($list), $acc));
    };
    return $iter($list, $acc);
}

function isPair($item)
{
    return is_callable($item);
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question