Skip to content

Instantly share code, notes, and snippets.

@griffinmyers
Last active January 21, 2018 05:21
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 griffinmyers/e03fbed31ba57ec4aaa7ee86a47ef689 to your computer and use it in GitHub Desktop.
Save griffinmyers/e03fbed31ba57ec4aaa7ee86a47ef689 to your computer and use it in GitHub Desktop.
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