Created
February 26, 2018 22:08
-
-
Save sjqtentacles/b4cb121b6aa42005e591c89c4e638c5a to your computer and use it in GitHub Desktop.
flatten an array of arbitrarily nested arrays of integers into a flat array of integers
This file contains 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(flatten_ints). | |
-export([flatten/1, test/0]). | |
% I also wrote a scala one from the prolog 99 problems set - but this was a while back | |
% located here: https://github.com/Nixonite/scala-99/blob/master/p07.scala | |
% base cases here | |
flatten([]) -> []; | |
flatten([[]|T]) -> flatten(T); | |
% if the head is a list, extract the head and continue | |
flatten([[X|Xs] | T]) -> | |
flatten([X|[Xs|T]]); | |
% alternatively, this code below could be used to concatenate the remaining two tail lists, but | |
% list concatenation is inefficient for any long lengths since these are linked lists | |
% but still, might be good if the lists are expected to be short? | |
% flatten([[X|Xs] | T]) -> | |
% flatten([X| (Xs ++ T)]). | |
% last case, extract the head and flatten the rest | |
flatten([H|T]) -> [H|flatten(T)]; | |
flatten(X) -> error. | |
% some gist-friendly test function | |
test() -> | |
[1,2,3] = flatten([1,2,[3]]), | |
[] = flatten([]), | |
error = flatten(3), | |
[3,4,5] = flatten([[3],[4],5]), | |
[1] = flatten([1]), | |
[1] = flatten([[[1]]]), | |
ok. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment