-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path12-functions.go
77 lines (60 loc) · 1.5 KB
/
12-functions.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* @Author: Barnabas Makonda
* @Date: 2019-01-15 22:46:35
* @Last Modified by: Barnabas Makonda
* @Last Modified time: 2019-01-15 23:05:36
*/
package main
import "fmt"
/*
*Function - an independent section of code that maps zero or more input parameters to zero or more output parameters.
*/
func average(xs []float64) float64 {
total := 0.0
for _, v := range xs {
total += v
}
return total / float64(len(xs))
}
// Return multiple values
func avarageTotal(xs []float64) (float64, float64) {
total := 0.0
for _, v := range xs {
total += v
}
return total, total / float64(len(xs))
}
// variadic functions
// By using ... before the type name of the last parameter you can indicate that it takes zero or more of those parameters.
// In this case we take zero or more ints.
// We invoke the function like any other function except we can pass as many ints as we want.
func add(args ...int) int {
total := 0
for _, v := range args {
total += v
}
return total
}
// Recursion - the ability of a function to call itself.
func factorial(x uint) uint {
if x == 0 {
return 1
}
return x * factorial(x-1)
}
func main() {
xs := []float64{98, 93, 77, 82, 83}
fmt.Println(average(xs))
total, avarage := avarageTotal(xs)
fmt.Println(total, avarage)
fmt.Println(add(1, 2, 3, 4))
// Closure - it is possible to create function within a function.
// and it can access other local variables
x := 0
increment := func() int {
x++
return x
}
fmt.Println(increment())
fmt.Println(factorial(3))
}