Search code examples
javascriptrecursionfunctional-programmingpointfreeramda.js

Refactoring getPermutations() of a String using recursion, Ramda.js and a point-free style


I've been attempting to refactor my original solution to a getPermutations() function using a point-free approach using Ramda.js. Is it possible to refactor it further, towards a point-free style. It looks like I just made an even bigger mess. Also, there is currently a bug in the refactored version when I run the tests: TypeError: reduce: list must be array or iterable.

Original Solution:

// getPermutations :: String -> [String]
function getPermutations(string) {
  function permute(combination, permutations, s) {
    if (!s.length) {
      return permutations[combination] = true;
    }

    for (var i = 0; i < s.length; i++) {
      permute( combination.concat(s[i])
             , permutations
             , (s.slice(0, i) + s.slice(i+1))
             );
    }
    return Object.keys(permutations);
  }

  return permute('', {}, string);
}

My attempt to refactor with Ramda.js:

var _ = require('ramda');

// permute :: String -> {String: Boolean} -> String -> [String]
var permute = _.curry(function (combination, permutations, string) {
  // callPermute :: String -> ({String: Bool} -> Char -> Int -> String) -> IO
  var callPermute = function (combination) {
    return function (acc, item, i, s) {
      return permute( _.concat(combination, item)
                    , acc
                    , _.concat(_.slice(0, i, s), _.slice(i + Infinity, s))
                    );
    };
  };

  var storeCombination = function () { 
    return permutations[combination] = true;
  };

  // should be an ifElse, incorporating compose below
  _.when(_.not(string.length), storeCombination);

  return _.compose( _.keys
                  , _.addIndex(_.reduce(callPermute(''), {}))
                  ) (string.split(''));
});

// getPermutations :: String -> [String]
var getPermutations = permute('', {});

Solution

  • There seem to be several problems with your solution, and I'm afraid I don't have time to chase them down. (The first thing I see is that you are using addIndex incorrectly.)

    But if you want to see a working permutation function in Ramda, I wrote this a while ago:

    // permutations :: [a] -> [[a]]
    const permutations = (tokens, subperms = [[]]) =>
      R.isEmpty(tokens) ?
        subperms :
        R.addIndex(R.chain)((token, idx) => permutations(
          R.remove(idx, 1, tokens), 
          R.map(R.append(token), subperms)
        ), tokens);
    
    R.map(R.join(''), permutations(['A', 'B', 'C'])); 
    //=> ["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]
    

    (You can play with this on the Ramda REPL.)