12
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP で関数合成

Last updated at Posted at 2012-12-26

2014-11-28 追記

関数合成については Composer からインストール可能な形で yuyat\compose というのを作ったので、そちらをご利用ください。

yuyat\compose は PHP 5.6 以降でないと使えませんが、それ未満のバージョンであれば igorw\compose を使うのが良いでしょう。


「関数型Ruby」という病(2) - 関数合成 Proc#compose という記事が面白かったので

compose.php
<?php
class ComposableFunction
{
    /**
     * @var callable
     */
    private $fn;

    /**
     * Constructor
     *
     * @param callable $fn
     */
    public function __construct(callable $fn)
    {
        $this->fn = $fn;
    }

    /**
     * Invokes function
     */
    public function __invoke()
    {
        return call_user_func_array($this->fn, func_get_args());
    }

    /**
     * Composes new function
     */
    public function compose(callable $fn)
    {
        return new static(function () use ($fn) {
            return $fn(call_user_func_array($this, func_get_args()));
        });
    }
}

$splitWithUnderscore = new ComposableFunction(function ($str) {
    return explode('_', $str);
});

$mapUcfirst = function ($words) {
    return array_map('ucfirst', $words);
};

$camelize = $splitWithUnderscore->compose($mapUcfirst)->compose('join');

var_dump($camelize('foo_bar_baz'));
// => FooBarBaz
12
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?