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