Haskell's list.permutations in TypeScript

Rosetta Stone: ruby/permutation

How to use

Install via yarn add locutus and import: import { permutations } from 'locutus/haskell/list/permutations'.

Or with CommonJS: const { permutations } = require('locutus/haskell/list/permutations')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1permutations([1, 2, 3])[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
2permutations(['a', 'b'])[['a', 'b'], ['b', 'a']]
3permutations([])[[]]

Notes

  • Returns all permutations, preserving Haskell’s empty-list behavior (one empty permutation).

Here's what our current TypeScript equivalent to Haskell's list.permutations looks like.

function permutationsInternal<T>(items: T[]): T[][] {
if (items.length === 0) {
return [[]]
}

const out: T[][] = []
for (let i = 0; i < items.length; i++) {
const current = items[i] as T
const rest = items.slice(0, i).concat(items.slice(i + 1))
for (const tail of permutationsInternal(rest)) {
out.push([current, ...tail])
}
}
return out
}

export function permutations<T>(items: T[] | unknown): T[][] {
// discuss at: https://locutus.io/haskell/list/permutations/
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Returns all permutations, preserving Haskell's empty-list behavior (one empty permutation).
// example 1: permutations([1, 2, 3])
// returns 1: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
// example 2: permutations(['a', 'b'])
// returns 2: [['a', 'b'], ['b', 'a']]
// example 3: permutations([])
// returns 3: [[]]

if (!Array.isArray(items)) {
return [[]]
}

return permutationsInternal(items.slice())
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


We have 2 Haskell functions so far - help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

  • Get inspiration from the Haskell base Data.List docs.
  • Click "New file" in the appropriate folder on GitHub. This will fork the project to your account, directly add the file to it, and send a Pull Request to us.

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.


« More Haskell list functions


Star