Task 9.6
-
In the
tasks/task9_6subdirectory of your repository is an Amper project for a program to compute variance in a numeric dataset. Source code files for this program are in thesrcsubdirectory of this project.Open the source code file named
Funcs.ktand add thevariance()function discussed earlier. Your implementation should test whether the provided list has enough values usingrequire(). -
To check that you’ve implemented
variance()correctly, go totasks/task9_6in a terminal window and run the unit tests for this function with./amper testMake sure the code compiles and the tests all pass before proceeding any further.
The tests are in
test/VarianceTest.kt. Take a few minutes to study this code.This is a ‘sneak peak’ at some of the more advanced features of Kotest, which we will cover in Unit Testing (Part 2)…
-
Add a function to
Funcs.ktthat will read data from a file and return it as a list ofDoublevalues:fun readData(filename: String) = buildList { File(filename).forEachLine { add(it.toDouble()) } }Note: you will also need to add
import java.io.Fileat the top ofFuncs.kt.Check that the code compiles with
./amper build -
Now open
Main.kt. In this file, write amain()function that expects a filename to be supplied on the command line. Your program should use thereadData()andvariance()functions to read a dataset from that file and then compute its variance. Your program should display both the size of the dataset and the variance, formatting the latter to five decimal places.Use
tryandcatchblocks orrunCatching()to intercept exceptions that might occur. Display some information about the caught exception and then terminate the program with a non-zero status code.Once again, check that the code compiles with
./amper build -
Try running the program without a command line argument, and then with the name of a file that doesn’t exist:
./amper run ./amper run file-that-does-not-existBoth of these should result in errors. The second of them should be dealt with by your exception handling code.
-
Create the following test files:
- An empty file
- A file containing a single number
- A valid file, containing only numbers (one per line)
- A file that mixes numeric & non-numeric data
Run the program on each of these, to check that it behaves as expected.