Skip to content

Instantly share code, notes, and snippets.

@griffinmyers

griffinmyers/flatten.re

Last active Jan 21, 2018
Embed
What would you like to do?
type node =
| ListOfNodes(list(node))
| Int(int)
| Nil;
let example =
ListOfNodes([
Int(1),
Nil,
ListOfNodes([
Int(2),
Int(3),
ListOfNodes([Int(4)]),
ListOfNodes([ListOfNodes([])])
])
]);
let rec stringOfNode = n =>
switch n {
| ListOfNodes(l) => "[" ++ stringOfList(l) ++ "]"
| Int(i) => string_of_int(i)
| Nil => "nil"
}
and stringOfList = l : string =>
List.fold_left(
(acc, n) => acc ++ (acc == "" ? "" : ", ") ++ stringOfNode(n),
"",
l
);
let rec flatten = n =>
switch n {
| ListOfNodes(l) => ListOfNodes(flattenList(l))
| Int(i) => Int(i)
| Nil => Nil
}
and flattenList = l =>
List.fold_left(
(acc, n) =>
switch n {
| ListOfNodes(l) => acc @ flattenList(l)
| Int(i) => acc @ [Int(i)]
| Nil => acc
},
[],
l
);
stringOfNode(example) |> print_string;
print_newline();
flatten(example) |> stringOfNode |> print_string;
print_newline();
[1, nil, [2, 3, [4], [[]]]]
[1, 2, 3, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment