update: advanced funcs

This commit is contained in:
Inanc Gumus
2019-05-03 23:04:56 +03:00
parent c39f15cb68
commit d2a957b67e
3 changed files with 45 additions and 16 deletions

View File

@ -7,7 +7,11 @@
package main
import "fmt"
import (
"fmt"
"strings"
"unicode"
)
type filterFunc func(int) bool
@ -23,6 +27,17 @@ func main() {
fmt.Println("\n••• FUNC VALUES •••")
fmt.Printf("evens : %d\n", filter(isEven, nums...))
fmt.Printf("odds : %d\n", filter(isOdd, nums...))
fmt.Println("\n••• MAPPING •••")
fmt.Println(strings.Map(unpunct, "hello!!! HOW ARE YOU???? :))"))
fmt.Println(strings.Map(unpunct, "TIME IS UP!"))
}
func unpunct(r rune) rune {
if unicode.IsPunct(r) {
return -1
}
return unicode.ToLower(r)
}
func filter(f filterFunc, nums ...int) (filtered []int) {
@ -33,6 +48,7 @@ func filter(f filterFunc, nums ...int) (filtered []int) {
}
return
}
func filterOdds(nums ...int) (filtered []int) {
for _, n := range nums {
if isOdd(n) {

View File

@ -22,7 +22,7 @@ func main() {
// ========================================================================
fmt.Println("\n••• FUNC LITERALS •••")
fmt.Println("\n••• CLOSURES •••")
var min int
greaterThan := func(n int) bool {
@ -35,16 +35,29 @@ func main() {
min = 6
fmt.Printf("> 6 : %d\n", filter(greaterThan, nums...))
// ========================================================================
// min = 1
// fmt.Printf("> 1 : %d\n", filter(greaterThan, nums...))
// min = 2
// fmt.Printf("> 2 : %d\n", filter(greaterThan, nums...))
// min = 3
// fmt.Printf("> 3 : %d\n", filter(greaterThan, nums...))
fmt.Println("\n••• HIGHER-ORDER FUNCS •••")
fmt.Printf("> 3 : %d\n", filter(greater(3), nums...))
fmt.Printf("> 6 : %d\n", filter(greater(6), nums...))
var filterers []filterFunc
for i := 1; i <= 3; i++ {
current := i
filterers = append(filterers, func(n int) bool {
min = current
return greaterThan(n)
})
}
printer(filterers, nums...)
}
func greater(min int) filterFunc {
return func(n int) bool {
return n > min
func printer(filterers []filterFunc, nums ...int) {
for i, filterer := range filterers {
fmt.Printf("> %d : %d\n", i+1, filter(filterer, nums...))
}
}

View File

@ -40,7 +40,7 @@ func main() {
fmt.Printf("dups uniqs : %v\n", filter(uniques(), out...))
dups = reverse(uniques())
chained := chain(reverse(greater(2)), dups, uniques())
chained := chain(reverse(greater(1)), dups, uniques())
fmt.Printf("dups chain : %v\n", filter(chained, 1, 1, 2, 3, 3, 3, 3, 0, 0))
}
@ -78,6 +78,12 @@ func greater(min int) filterFunc {
}
}
func lesseq(max int) filterFunc {
return func(n int) bool {
return n <= max
}
}
func filter(f filterFunc, nums ...int) (filtered []int) {
for _, n := range nums {
if f(n) {
@ -89,9 +95,3 @@ func filter(f filterFunc, nums ...int) (filtered []int) {
func isEven(n int) bool { return n%2 == 0 }
func isOdd(m int) bool { return m%2 == 1 }
func lesseq(max int) filterFunc {
return func(n int) bool {
return n <= max
}
}