Skip to content

Instantly share code, notes, and snippets.

@raliste
Last active August 29, 2015 14:03
Show Gist options
  • Save raliste/db0a1df1dab809834a5d to your computer and use it in GitHub Desktop.
Save raliste/db0a1df1dab809834a5d to your computer and use it in GitHub Desktop.
Ejercicio 1
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