Skip to content

Instantly share code, notes, and snippets.

@kraftdorian
Created April 5, 2021 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kraftdorian/8b31ac73fed314ba6e014f486b454125 to your computer and use it in GitHub Desktop.
Save kraftdorian/8b31ac73fed314ba6e014f486b454125 to your computer and use it in GitHub Desktop.
Recursive list reverse in JavaScript written in Prolog style
const usePrologStyleList = (array) => {
const [head, ...tail] = array;
return [head, tail];
};
const listReverseState = (list, reversedList, acc) => {
const [head, tail] = usePrologStyleList(list);
if (head === undefined) {
return reversedList = acc;
}
return listReverseState(tail, reversedList, [head].concat(acc));
};
const listReverse = (list) => listReverseState(list, [], []);
@kraftdorian
Copy link
Author

This script is based on this Prolog program.

Use case:

const reversedList = listReverse([1, 2, 3, 4, 5]);
console.log(reversedList);

Result:

[ 5, 4, 3, 2, 1 ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment