Created
August 19, 2011 05:58
-
-
Save jtrim/1156151 to your computer and use it in GitHub Desktop.
Erlang nested list comprehensions - an anagram example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -module(listcomp). | |
| -export([perms/1]). | |
| % generates all possible letter permutations given a string of letters | |
| perms( [] ) -> [[]]; | |
| perms(Phrase) -> | |
| [ [H|Rest] || | |
| H <- Phrase, | |
| Rest <- perms(Phrase -- [H])]. | |
| % Explanation with "word" as Phrase (for my own understanding, some real code, some pseudo): | |
| % At the deepest level of recursion, perms([]) will return [[]]. | |
| % Up one level - perms("d") means H == "d" and Rest == perms("d" -- "d") | |
| % (which is the same as % perms([]) ), so perms("d") == [ [$d|[]] ] == ["d"]. | |
| % Step up one level, using "rd" as Phrase. perms("rd") will mean that for | |
| % one iteration, H == "r" and Rest == ["d"], which results in "rd". For the | |
| % next iteration, H == "d" and Rest == ["r"], which results in "dr". So | |
| % perms("rd") == [ "rd", "dr" ]. | |
| % Step up yet another level, using perms("ord"). For the first iteration, | |
| % H == "o" and Rest == [ "rd", "dr" ], so "o" is mapped to "ord", "odr". After | |
| % the first iteration, we have: | |
| % [ "ord", "odr" | |
| % For the next iteration, H == "r" and Rest == [ "od", "do" ]. After the | |
| % second iteration, we have: | |
| % [ "ord", "odr", "rod", "rdo" | |
| % For the third iteration, H == "d" and Rest == [ "or", "ro" ]. After the third | |
| % iteration, we have: | |
| % [ "ord", "odr", "rod", "rdo", "dor", "dro" ] | |
| % Step up one more level, using perms("word"). For the first iteration, H == "w" and | |
| % Rest == [ "ord", "odr", "rod", "rdo", "dor", "dro" ]. After the first iteration, we | |
| % have: | |
| % [ "word", "wodr", "wrod", "wrdo", "wdor", "wdro" | |
| % and so on. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment