Solution: Function composition
- [Instructor] Let's talk about the implemented CalculateVariance function based on the structure we've already discussed. We'll start with the error case. On line 18, I use an IF statement to check whether the number slice is nil or empty. In this case, it will return nil for the result and return an error. On line 21, I declare the variable n which will hold the number of elements as a float64 type. This will make it easier for us to calculate the mean and variance without having to cast the length to float64 multiple times. As you remember from challenge one, the float64 type is required to calculate decimal point numbers. Next, I'll implement our sum inside the scope of the CalculateVariance function. This function takes in a function f as a parameter and returns a float64. The function f itself takes in a single int parameter and returns a float64. The function parameter makes it easier for us to calculate sums of different types and reduce the amount of code we write. Just as we've done in challenge one, I declare the s variable which will hold our sum on line 23 and loop over the numbers parameter using the range operator on lines 24 to 26. The loop discards the index and saves the value into the num variable. Inside the loop, I apply the function f to the num parameter and add it to the sum variable using the plus equal operator. Finally, once the loop has completed, I return the calculated sum on line 27. With the building blocks in place, I'm ready to calculate the mean. On lines 29 to 31, I call the sum function which takes in a function parameter. The function will simply return its parameter i cast as float64. Then I divide the computed sum by the defined length variable n. On lines 32 to 34, I can proceed with the calculation of the sum of residuals in the same way. I'll use the sum function which takes in a function parameter. This function calls the math.Pow function and squares the difference between i and the mean. Then I cast the values of the parameter as float64 type again. Finally, the variance is computed on line 35 by dividing the sum of residuals with the float64 length variable n. I return a pointer to the computed variance and a nil error on line 36. That's all the code we need to write to calculate the variance. Let's try out our function by using the Test My Code button. The function returns the expected values.
随堂练习,边学边练
下载课堂讲义。学练结合,紧跟进度,轻松巩固知识。