Created
April 4, 2020 14:20
-
-
Save jannesiera/f6aefdd59cdd26271ab2968921fc7779 to your computer and use it in GitHub Desktop.
Flatten arbitrarily nested lists 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
// Data structures | |
type Node = | |
| Int of int | |
| Nodes of Node list | |
// Behavior | |
module Node = | |
// private helper | |
let rec private flattenNodesRec nodes result = | |
match nodes with | |
| [] -> result | |
| x::xs -> | |
let newsubnodes, newresult = | |
match x with | |
| Int v -> xs, result @ [v] | |
| Nodes subnodes -> subnodes @ xs, result | |
flattenNodesRec newsubnodes newresult // Tail-call position | |
// flattenNodes will take a list of nodes and return a single list of int's | |
// It is tail-call optimized | |
let flattenNodes nodes = flattenNodesRec nodes [] | |
// Test | |
let input = [ | |
Nodes [ | |
Int 1 | |
Int 2 | |
Nodes [ | |
Int 3 | |
] | |
] | |
Int 4 | |
] | |
let output = Node.flattenNodes input | |
let expected = [ 1; 2; 3; 4 ] | |
let testPassed = (output = expected) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment