Last active
October 14, 2016 18:59
-
-
Save caelifer/641aa9c54c823a7c43a775beac12a4bf to your computer and use it in GitHub Desktop.
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" | |
"strings" | |
) | |
func main() { | |
strs := StringSlice{"Hello", "foo", "bar"} | |
ints := IntSlice{1, 2, 3, 4} | |
// Example use Map with custom and stdlib functions | |
excl := func(s string) string { return s + "!" } | |
fmt.Println(strs, "->", strs.Map(excl)) | |
fmt.Println(strs, "->", strs.Map(strings.Title)) | |
// Example using Map->Grep chain | |
hasOh := func(s string) bool { return strings.ContainsAny(s, "Oo") } | |
fmt.Println(strs, "->", strs.Map(strings.ToLower).Grep(hasOh)) | |
// Same examples for ints | |
double := func(i int) int { return i * 2 } | |
fmt.Println(ints, "->", ints.Map(double)) | |
tripple := func(i int) int { return i * 3 } | |
even := func(i int) bool { return i&0x1 == 0 } | |
fmt.Println(ints, "->", ints.Map(tripple).Grep(even)) | |
// Type mismatch eror case | |
fmt.Println(ints, "->", ints.Map(tripple).Grep(even).Grep(hasOh)) | |
} | |
//////////////////////////////// | |
//// -- Type definitions -- //// | |
//////////////////////////////// | |
type Mapper interface { | |
Map(transformer interface{}) Functional | |
} | |
type Grepper interface { | |
Grep(predicate interface{}) Functional | |
} | |
type Functional interface { | |
Mapper | |
Grepper | |
} | |
type StringSlice []string | |
func (slice StringSlice) Map(f interface{}) Functional { | |
res := StringSlice(make([]string, 0, len(slice))) | |
fn := f.(func(string) string) | |
for _, v := range slice { | |
res = append(res, fn(v)) | |
} | |
return res | |
} | |
func (slice StringSlice) Grep(p interface{}) Functional { | |
res := StringSlice(make([]string, 0, len(slice))) | |
fn := p.(func(string) bool) | |
for _, v := range slice { | |
if fn(v) { | |
res = append(res, v) | |
} | |
} | |
return res | |
} | |
type IntSlice []int | |
func (slice IntSlice) Map(f interface{}) Functional { | |
res := IntSlice(make([]int, 0, len(slice))) | |
fn := f.(func(int) int) | |
for _, v := range slice { | |
res = append(res, fn(v)) | |
} | |
return res | |
} | |
func (slice IntSlice) Grep(p interface{}) Functional { | |
res := IntSlice(make([]int, 0, len(slice))) | |
fn := p.(func(int) bool) | |
for _, v := range slice { | |
if fn(v) { | |
res = append(res, v) | |
} | |
} | |
return res | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Live example - https://play.golang.org/p/AR1u7EXkno
Output: