Skip to content
This repository was archived by the owner on May 29, 2023. It is now read-only.

Add bind() function #6

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open

Add bind() function #6

wants to merge 12 commits into from

Conversation

shadowhand
Copy link
Contributor

Actual changes are in 5d69102

Fixes #5
Refs #4

shadowhand added 12 commits June 1, 2017 09:13
Having an immutable `Curry` class allows creating a curry from any
callable. Having this as a base class will allow additional
functionality such as `Partial` to be added with minimal effort.
Having all combinators curried by default provides much greater
flexibility for point-free programming.
@jrsinclair
Copy link

Would it make more sense to rename bind() to partial(), as you suggest in #5? If we were to implement a function called bind, then I would have assumed its primary function would be to call a method on a given object (as with JavaScript). For example:

<?php
class Identity {

    private $_val;

    public function __construct($val) {
        $this->val = $val;
    }

    public function map($f) {
        return new Identity($f($this->val));
    }

    public function chain($f) {
        return $f($this->val);
    }
}

function bind($method_name, $obj) {
    return function () use ($method_name) {
        $params = func_get_args();
        return call_user_func_array(array($obj, $method_name), $params);
    }
}

$i1        = new Identity(1);
$add1      = function ($x) { return $x + 1; };
$times3    = function ($x) { return new Identity($x * 3); };
$mapOnI1   = bind('map', $i1);
$chainOnI1 = bind('chain', $i1);
$i2        = $mapOn1($add1);     // Identity(2)
$i3        = $chainOn1($times3); // Identity(3)

@i-am-tom
Copy link

I'm not sure it makes sense - if you're going to write curried PHP, wouldn't you write them as nested functions anyway? (Genuine question - I haven't touched PHP in about 2 years now)

@jrsinclair
Copy link

My point was more about how the function is named. I think it should be called partial() rather than bind(). My reasoning was to prevent confusion for people coming from JavaScript, who might expect a function named bind() to work a bit differently to partial().

Whether or not you need a partial() when you've got curried functions is another question. You certainly don't need it. As @i-am-tom points out, you can just return a nested function. But I can think of some use cases where it might come in handy. It would be a convenience more than anything.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants