Solution Review: Filter Even and Odd Numbers
This lesson discusses the solution to the challenge given in the previous lesson.
We'll cover the following...
We'll cover the following...
Go (1.6.2)
package mainimport "fmt"type flt func(int) bool // aliasing typefunc isEven(n int) bool { // check if n is even or notif n % 2 == 0 {return true}return false}func filter(sl[] int, f flt)(yes, no[] int) { // split s into two slices: even and oddfor _, val := range sl {if f(val) {yes = append(yes, val)} else {no = append(no, val)}}return}func main() {slice := [] int {1, 2, 3, 4, 5, 7}fmt.Println("slice = ", slice)even,odd := filter(slice, isEven)fmt.Println("The even elements of slice are: ", even)fmt.Println("The odd elements of slice are: ", odd)}
The program above has one basic function. The function isEven takes n
as a parameter and returns a boolean value (see its header at line6). If n
is even, it will return true; otherwise, it will return false. At line 4 ...