Skip to content

Instantly share code, notes, and snippets.

@jannesiera
Created April 4, 2020 14:20
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 jannesiera/f6aefdd59cdd26271ab2968921fc7779 to your computer and use it in GitHub Desktop.
Save jannesiera/f6aefdd59cdd26271ab2968921fc7779 to your computer and use it in GitHub Desktop.
Flatten arbitrarily nested lists of integers
// 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