Last active
August 29, 2015 14:03
-
-
Save raliste/db0a1df1dab809834a5d to your computer and use it in GitHub Desktop.
Ejercicio 1
This file contains hidden or 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 ( | |
"log" | |
"reflect" | |
) | |
// Implements map by closure | |
type Mapper func(interface{}) interface{} | |
func Map(data []interface{}, fn Mapper) []interface{} { | |
l := len(data) | |
for i:=0; i<l; i++ { | |
data[i] = fn(data[i]) | |
} | |
return data | |
} | |
// Implements map by composition | |
type Enumerator interface { | |
Map(interface{}) interface{} | |
} | |
func EnumeratorMap(data Enumerator) interface{} { | |
t := reflect.ValueOf(data) | |
arr := make([]interface{}, t.Len()) | |
for i:=0; i<t.Len(); i++ { | |
arr[i] = data.Map(t.Index(i).Interface()) | |
} | |
return arr | |
} | |
type T []int | |
func (t T) Map(datum interface{}) interface{} { return datum.(int)*2 } | |
func main() { | |
// By composition | |
t := T{1,2,3} | |
results := EnumeratorMap(t) | |
log.Println(results) | |
// By closure | |
results = Map([]interface{}{"a", "b", "c"}, func(datum interface{}) interface{} { | |
return interface{}("PREY" + datum.(string)) | |
}) | |
log.Println(results) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment