Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Task 9.6

  1. In the tasks/task9_6 subdirectory 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 the src subdirectory of this project.

    Open the source code file named Funcs.kt and add the variance() function discussed earlier. Your implementation should test whether the provided list has enough values using require().

  2. To check that you’ve implemented variance() correctly, go to tasks/task9_6 in a terminal window and run the unit tests for this function with

    ./amper test
    

    Make sure the code compiles and the tests all pass before proceeding any further.

    Note

    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)

  3. Add a function to Funcs.kt that will read data from a file and return it as a list of Double values:

    fun readData(filename: String) = buildList {
        File(filename).forEachLine {
            add(it.toDouble())
        }
    }
    

    Note: you will also need to add import java.io.File at the top of Funcs.kt.

    Check that the code compiles with

    ./amper build
    
  4. Now open Main.kt. In this file, write a main() function that expects a filename to be supplied on the command line. Your program should use the readData() and variance() 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 try and catch blocks or runCatching() 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
    
  5. 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-exist
    

    Both of these should result in errors. The second of them should be dealt with by your exception handling code.

  6. 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.