Created
January 17, 2016 20:51
-
-
Save adria0/ff3cf756e5bbe674dbf2 to your computer and use it in GitHub Desktop.
Golang flattener experiment
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
package main | |
import "fmt" | |
import "errors" | |
// Function to flatten nested arrays of integers | |
// Nested arrays of integers are encoded as arrays of interface{} | |
func flatten(elements []interface{}) ([]int, error) { | |
intarray := []int{} | |
var flattenn func(elements []interface{}) error | |
flattenn = func(elements []interface{}) error { | |
for i := range elements { | |
switch elements[i].(type) { | |
case int: | |
intarray = append(intarray, elements[i].(int)) | |
case []interface{}: | |
slice := elements[i].([]interface{}) | |
if err := flattenn(slice); err != nil { | |
return err | |
} | |
default: | |
return errors.New("Invalid elements argument in flatten") | |
} | |
} | |
return nil | |
} | |
if err := flattenn(elements); err != nil { | |
return nil, err | |
} else { | |
return intarray, nil | |
} | |
} | |
// Helper function to create arrays of anything | |
func bundle(elements ...interface{}) []interface{} { | |
return elements | |
} | |
func main() { | |
elements := bundle(bundle(1, 2, bundle(3)), 4) | |
intarray, err := flatten(elements) | |
fmt.Println("Error: ", err, " / In: ", elements, " -> Out :", intarray) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment