Struggling with flatten function.
"Douglas Lewit [email protected] [ocaml_beginners]" <[email protected]> Thu, 29 Sep 2016 15:10:56 -0500
| Newsgroups | gmane.comp.lang.ocaml.beginners |
|---|---|
| Message-ID | <CAM0XMJQFx=Yqw3KXC7Z=0BP7ETmDx8y82t+7wCPzr9GbSj-PNQ@mail.gmail.com> |
So I figured out the following:
let rec flatten = function
|[ ] -> [ ]
|head :: tail -> head @ flatten tail ;;
This mimics the builtin List.flatten function from the List module.
BUT.... that function only applies to lists nested within a bigger list.
So the flatten function peels away the outer "list skin" so to speak. But
the function doesn't help with something like this:
[ [[1]; [2]; [3]] [[4; 5; 6]]; [[7]]; [[8]]; [[9]] ] because this is really
an int list list list! Yes, the flatten function works if we apply it
twice, but how would some other function know to flatten the list twice?
In terms of imperative logic I'm trying to continually flatten the list
until there's no change.... but that will generate an Error and I don't
know how to handle that. Okay, this is confusing! Any suggestions on how
to repeatedly flatten a list until we can't flatten it any longer?
Thanks!!!
Best,
Douglas Lewit