Search code examples
phpfunctional-programmingcurryingpartial-application

Currying in_array() in PHP


Don't necessarily have a problem with how PHP does this or anything, more just a question out of curiosity. I am familiar with functional programming but am by no means an expert. I am writing functions currently and although I have no requirement for them to be functional, that may change in the future. So best to be prepared I say.

My question is, how would you curry a function like in_array?

From what I understand we have two parameters, needle and haystack.

Both seem to be required when the function is called.

We must know the array we are searching at the start of the function, and we must also know what we are searching for.

To me it seems hard to force any partial application or currying solution whereby we might know one or the other at a later point.

I suppose you could have a non-generic function whereby you specify the needle within the function. I did see something about spattering in Google. How would you handle this if asked to rewrite the function and curry it? I know I specified PHP but I suppose any language is really fine as long as the specs are the same.


Solution

  • Well, it's relatively straightforward in PHP - almost the same as in any other language that treats functions as values. For example:

    function create_search_by_array($arr) {
      return function($needle) use ($arr) {
        return in_array($needle, $arr);
      };
    }
    
    $search_in_1_to_10 = create_search_by_array(range(1, 10));
    var_dump($search_in_1_to_10(1)); // true
    var_dump($search_in_1_to_10(10)); // true
    var_dump($search_in_1_to_10(11)); // false
    

    The only caveat here is use ($arr) construct: without it, the inner function won't be able to see the corresponding variable from an outer scope.