UNB/ CS/ David Bremner/ teaching/ cs2613/ labs/ CS2613 Labs

Labs

Lab 1

Before the lab

Before every lab in this course, you will be given tasks to complete. These will generally be easy tasks like watching videos, but you need to complete them in order to keep up with the class.

Command Line Familiarity Check

  1. In an FCS linux lab (remote or locally) log in, and open a terminal.

  2. Make a directory

  3. Create a file in that directory using one of the available text editors

  4. Now clean up, removing the file and the directory.

If any of this was new to you, then please take the time to go through parts 1 to 5 of the Learning the Shell Tutorial.

Read the course syllabus.

The Course Syllabus is available on line. Please read it, and bring any questions you have about it to the first lab.

Background Reading

For every lab there will be some related reading. I'll point these out as we go through the lab, but I'll also collect them at the start of the lab in case you want to get a head start (or refer back to them later).


About the course

Time
10 minutes
Activity
Q&A, discuss course syllabus.
  1. What's similar to other CS courses you've taken?

  2. What's different?

  3. Key point, how are labs evaluated?

Getting started with racket

  1. Open a terminal.

  2. Make a directory called cs2613 that will keep all of your work (note that case and spaces matter in Linux and this is not the same as CS2613 or CS 2613. For the rest of this course we will assume it is directly under your home directory. The shortcut ~/cs2613 will refer to this directory in the lab texts and in the shell.

Hello Racket World

Time
20 Minutes
Activity
Group walkthrough
  • Open a terminal

  • Make a directory ~/cs2613/labs/L01 (if it does not already exist) and change there with cd

  • Save the following code to ~/cs2613/labs/L01/hello.rkt

#lang htdp/bsl
"hello world"
(* 6 7)

Command Line

  • run the program with

      $ racket hello.rkt
    
  • What is the difference between the first and second line of output?

  • compile the program

      $ raco make hello.rkt
    
  • run the program again

      $ racket hello.rkt
    
  • can you tell any difference? (hint, consider the "time" command).

DrRacket: A Racket Specific IDE

  • Start DrRacket from the activities menu

  • Referring to the DrRacket documentation as needed, open and run the hello.rkt program from the previous part.

  • What is the meaning of the first line of the file?

Setting up a git repo

Time
20 minutes
Activity
Individual work
Summary
This is where we create the git repository used for the rest of the term to hand things in.
  1. Change to ~/cs2613. This directory should have one subdirectory called labs, which has the results of our experiments with racket.

  2. Create the git repository

     $ git init -b main
    

    Git will reply with something like

     Initialized empty Git repository in /home1/ugrads/$username/cs2613/.git/
    

    You’ve now initialized the working directory — you may notice a new directory created, named ".git". You should mentally replace "$username" with whatever the login name is that you use to log into the FCS linux machines.

  3. Read the git-quickref page, and follow the initial configuration steps there.

    • note that the "--wait" option for gedit is important here.
  4. Next, tell Git to take a snapshot of the contents of all files under the labs, with git add:

    $ git add labs
    
Notes
Many revision control systems provide an add command that tells the system to start tracking changes to a new file. Git’s add command does something simpler and more powerful: git add is used both for new and newly modified files, and in both cases it takes a snapshot of the given files and stages that content in the index, ready for inclusion in the next commit.

This snapshot is now stored in a temporary staging area which Git calls the "index". You can permanently store the contents of the index in the repository with git commit:

   $ git commit

This will open and editor and prompt you for a commit message. Enter one and exit the editor. You’ve now stored the first version of your project in Git. See §5.2 of Pro Git for some hints about writing good commit messages. As mentioned in the class git policy, you will be marked on your commit messages, so you may as well get started with good habits.


Pushing to a central repo

Summary
Learn how to upload your work to a server
Time
20 minutes
Activity
Individual work
Notes
You absolutely have to understand this before continuing in the course, since all marks in the course will be based on work pushed to the coursegit repos.

Since we are using the FCS git repositories there is an existing repository for all students who registered early enough. If it turns out there is no repository for you, you may need to do the last step later.

  • First add the remote. This something like a nickname for the URL where the repo will be stored.

      $ git remote add origin https://$username@vcs.cs.unb.ca/git/cs2613-$username
    

    origin is the default name for a remote, but we could have used a different name here. Replace $username with your FCS Linux account name.

  • Now upload your local copy of the repo.

      $ git push --all origin
    

    you should see something like

              Counting objects: 388, done.
              Delta compression using up to 8 threads.
              Compressing objects: 100% (350/350), done.
              Writing objects: 100% (388/388), 71.63 KiB | 0 bytes/s, done.
              Total 388 (delta 223), reused 59 (delta 33)
              To https://$username@vcs.cs.unb.ca/git/cs2613-$username
                 e7e5311..f1ae959  main -> main
    

Git Tutorial Continued

Making Changes in git

Time
15 minutes
Activity
Individual work
Summary
Get some practice commiting your changes to git.

Change to the root of your git repository (~/cs2613). Start by finding the right files to edit with

$ git grep hello

git grep is a very useful (and fast!) tool to find occurrences of strings in your git repository. Notice in the output there are some Binary files created by racket; we will clean those up later.

Edit the non-binary (source code) file, and change the output message.

Use git add to stage your changes:

$ git add file1 

(replace file1 with the actual file you modified). You are now ready to commit. You can see what is about to be committed using git diff with the --cached option:

$ git diff --cached

or $ git diff --cached --stat

To undo the effect of a git add command, run git reset.

(Without --cached, git diff will show you any changes that you’ve made but not yet added to the index.) You can also get a brief summary of the situation with git status:

$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       modified:   file1
#       modified:   file2
#       modified:   file3
#

The git-rubric requies to begin the commit message with a single short line summarizing the change, followed by a blank line and then a more thorough description. The text up to the first blank line in a commit message is treated as the commit title, and that title is used throughout Git.

If you need to make any further adjustments, do so now, and then add any newly modified content to the index. Finally, commit your changes with:

$ git commit

This will again prompt you for a message describing the change, and then record a new version of the project.

Alternatively, instead of running git add beforehand, you can use

$ git commit -a

which will automatically notice any modified (but not new) files, add them to the index, and commit, all in one step. Keep in mind that you will be marked on the logical structure of your git commits, so you are better off using git add to explicitely choose what changes to commit.

Cleaning up generated files

Time
15 minutes
Activity
Individual work
Summary
Get some practice commiting your changes to git.

A common phenomenon in software development is the existence of generated files. These files are created by some tool, typically based on some source files. In general it is a bad idea to track generated files in version control because they introduce spurious changes into history. We'll look at this more later, but for now let's try to clean up. We can often find what files are generated by re-running the build process. In our case

$ cd ~/cs2613/labs/L01
$ raco make hello.rkt

To find out what changed, run

$ git diff --stat

All going well, you will two modified files. You can delete them using git rm. As with with other changes, you can preview your changes with git diff and git status.

When you are satisfied with the changes, run git commit.

Before next lab

Lab 2

Before the lab

Background


Viewing project history

Time
15 minutes
Activity
Small group discussion, presenting work to the group, peer feedback
Summary
Reinforce idea of commit message quality
  1. At any point you can view the history of your changes using

     $ git log
    

    Use this command to verify that all the changes you expected to be pushed to the server really were.

    If you also want to see complete diffs at each step, use

     $ git log -p
    

    Often the overview of the changes is useful to get a feel for each step

     $ git log --stat --summary
    
  2. In most projects, you have to share commit messages to (at least) the same people who view your source code. Share your "best commit" message with one or more of your neighbours.

  3. Find something positive to say about the other commit messages you are reading.

  4. Find a constructive improvement with one of the other messages. Don't be mean, people have varying levels of experience with this.

Racket

Racket Expressions.

Time
20 minutes
Activity
Small groups
#lang htdp/bsl
(define y 18)
(define (t1 x)
  (or (= x 0) (< 0 (/ y x))))
(define (t2 x)
  (or (< 0 (/ y x)) (= x 0)))
(define (t3 x)
  (and (= x 0) (< 0 (/ y x))))
(define (t4 x)
  (or (< 0 (/ y x)) (not (= x 0))))

Racket functions

Time
20 minutes
Activity
Individual work
(check-expect (middle-of-three 1 2 3) 2)
(check-expect (middle-of-three 2 1 3) 2)
(check-expect (middle-of-three 1 3 2) 2)

The DrRacket stepper

Time
25 minutes
Activity
Individual work

Test Coverage

Time
25 minutes
Activity
Individual work

Unit testing is an important part of programming, and has inspired something called test driven development.

Before Next Lab

Assignments

Reading

Lab 3

Before the lab

Assignments

Reading


Q&A

Time
5 Minutes
Activity
Group discussion

Setup


Semantics

Time
25 minutes
Activity
Small Groups
Summary
new evaluation rules for and and or

As you read in FICS unit 3, we can understand evaluation ("running") of Racket programs as a sequence of "reductions" or "substitutions". These rules are similar to the reduction steps in the DrRacket stepper.

The stepper uses the following rules for and and or (notice that these rules enforce short circuit evaluation)

(and true exp2 ...) => (and exp2 ...)
(and false exp2 ...) => false
(or true exp2 ...) => true
(or false exp2 ...) => (or exp2 ...)
(and) => true
(or) => false

Following Exercise 7, write a new set of rules that requires at least two arguments for and and or. The rules are for human consumption; you can write them as comments in DrRacket. You can write "exp1 exp2 ..." to mean at least 2 expressions.

Discuss your answers with a your group, and try a couple evaluation small examples by hand using your rules.

Simulating Natural Numbers I

Time
25 minutes
Activity
Individual work
Summary
Learn about structures and recursion.

Write the times function from Exercise 11 in FICS. You can (and should) use the following code from the linked discussion

#lang htdp/bsl
(define-struct Z ())
(define-struct S (pred))
(define (pred nat)
  (cond
    [(Z? nat) (error "can't apply pred to Z")]
    [(S? nat) (S-pred nat)]))

(define (plus nat1 nat2)
  (cond
    [(Z? nat1) nat2]
    [(S? nat1) (make-S (plus (S-pred nat1) nat2))]))

Here is the template for structural recursion on (simulated) natural numbers. See the linked text (or the plus function just above) for how to add a second "carried-along" parameter.

(define (my-nat-fn nat)
  (cond
    [(Z? nat) ...]
    [(S? nat) ... (my-nat-fn (S-pred nat)) ...]))

Here are some tests to get you started. As always, try to have as complete test coverage as possible. Depending on how you choose the language in DrRacket, the line (define-struct S (pred)) may show partial coverage; you can ignore this for this lab.

;; 0 * 0 = 0
(check-expect (times (make-Z) (make-Z)) (make-Z))
;; 0 * 1 = 0
(check-expect (times (make-Z) (make-S (make-Z))) (make-Z))
;; 2 * 1 = 2
(check-expect (times (make-S (make-S (make-Z)))
                       (make-S (make-Z)))
              (make-S (make-S (make-Z))))

You may find it helpful to refer back to your solution from L02.

Simulating Natural Numbers II

Time
30 minutes
Activity
Individual work
Summary
Learn about structures and recursion.

Write the compare function from Exercise 11 in FICS. Your function compare should use the struct definitions Z and S, and pass the following tests

;; 0 = 0
(check-expect (compare (make-Z) (make-Z)) 'equal)
;; 0 < 1
(check-expect (compare (make-Z) (make-S (make-Z))) 'less)
;; 1 > 0
(check-expect (compare (make-S (make-Z)) (make-Z)) 'greater)
;; 2 > 1
(check-expect (compare (make-S (make-S (make-Z)))
                       (make-S (make-Z))) 'greater)

Before Next Lab

Reading

On your own

Time
20 min
Activity
Independent research

See if you can come up with answers to the following questions for discussion in Lab 4.

  • The programming languages we will study this term are mainly dynamically typed. This means that not only the value but also the type of variables can change at runtime. Why does this make testing even more important?

  • What kind of software problems is testing not well suited to find?

  • Why might mutable state (e.g. instance variables in Java) make writing unit tests harder?

Lab 4

Before the lab

Reading

On your own

Time
20 min
Activity
Independent research

See if you can come up with answers to the following questions for discussion in Lab 4.

  • The programming languages we will study this term are mainly dynamically typed. This means that not only the value but also the type of variables can change at runtime. Why does this make testing even more important?

  • What kind of software problems is testing not well suited to find?

  • Why might mutable state (e.g. instance variables in Java) make writing unit tests harder?


Questions about testing

Time
10 Minutes
Activity
Group discussion

Setup

Structural recursion, on numbers

Time
20 minutes
Activity
Individual work
Summary
Learn about structural recursion.

Use structural (note that structural here is only indirectly related to Racket structs) recursion on natural numbers (not the simulated ones from above, but regular Racket numbers like 1, 42, and 1337) to define a function (sum-factors n max-factor) that sums all factors of n (including 1) no larger than max-factor

Recall the template for structural recursion on natural numbers:

(define (my-nat-fn n)
  (cond
    [(zero? n) ...]
    [(positive? n) ... (my-nat-fn (sub1 n)) ...]))

Try to use only one recursive call to sum-factors like in the template. Keep in mind that the n in the template might be a different parameter of your function. You can use the builtin function remainder to test for divisibility.

The following tests should pass

;; 1+2+3 = 6
(check-expect (sum-factors 6 5) 6)
;; 1+2+4+7+14 = 28
(check-expect (sum-factors 28 27) 28)

Substitute in a list

Time
25 minutes
Activity
Individual work
Summary
Learn about lists and recursion.

Complete FICS Exercise 13.

Note the template for structural recursion.

(define (my-list-fn lst)
  (cond
    [(empty? lst) ...]
    [(cons? lst) ... (first lst) ...
                 ... (my-list-fn (rest lst)) ...]))

Here is a test case based on the linked test

(check-expect
 (substitute 3 "three" (list "four" 3 4 "three" 3))
 (list "four" "three" 4 "three" "three"))

Uniquifying lists

Time
25 minutes
Activity
Individual work
Summary
Learn about lists and recursion.

Complete FICS Exercise 15. Although probably not intended by the original question, use the built-in BSL function member? to simplify your solution. Otherwise use only the constructs specified in Exercise 14, and structural recursion. Here is one test case derived from the linked text.

(check-expect
 (unique-right
  (list 1 4 2 1 5 4))
 (list 2 1 5 4))

Add an element to all lists

Time
25 minutes
Activity
Individual work
Summary
Learn about lists and recursion.

Recall the template for structural recursion on lists

(define (my-list-fn lst)
  (cond
    [(empty? lst) ...]
    [(cons? lst) ... (first lst) ...
                 ... (my-list-fn (rest lst)) ...])

Use this template to write a function cons-all that adds a given element to the front of each given sublist. This is related to FICS Exercises 23-25 (but you only need to write cons-all, not do those exercises).

The following test case illustrates the use of cons-all. You will need to use the language #lang htdp/bsl+ or "Beginning Student with List Abbreviations" or replace the use of ' in the following.

(check-expect (cons-all 3 '((2 4) () (5)))
              '((3 2 4) (3) (3 5)))

Before Next Lab

Lab 5

Before the lab


Questions

Time
5 Minutes
Activity
Group discussion / Announcments

Setup

Structural recursion on two parameters

Time
35 minutes
Activity
Small groups
Summary
Learn about lists and recursion.

Intersection of two ordered lists

Time
35 minutes
Activity
Individual work
Summary
Learn about lists and recursion.

The template for structural recursion on two lists is

(define (my-list-fn lst1 lst2)
  (cond
    [(empty? lst1) ... lst2 ...]
    [(empty? lst2) ... lst1 ...]
    [(cons? lst1)
        ... (first lst1) ... (first lst2) ...
        ... (my-list-fn (rest lst1) lst2) ...
        ... (my-list-fn lst1 (rest lst2)) ...
        ... (my-list-fn (rest lst1) (rest lst2)) ...]))

Use this template to complete FICS Exercise 20 You may find it helpful to refer to the function o-union defined in Section 5.4. Note that the fact that the lists are sorted is key an efficient solution here; you do not have to check that property.

Here are some test cases for the function intersection

(check-expect (intersection (list 1 2 3 4 5) (list 2 4 6 7))
              (list 2 4))

(check-expect (intersection (list 2 4 11) (list 1 2 3 4 5))
              (list 2 4))

Generating all subsets of fixed size

Time
35 minutes
Activity
Individual work
Summary
Learn about lists and recursion.

Start with the template from the first exercise and complete FICS Exercise 24. If your template needs updating, compare with cases in the two list template.

Use the built-in function append and the function cons-all you wrote in L04.

Here are some test cases to illustrate the use of the function comb

(check-expect (comb '(a) 1) '((a)))
(check-expect (comb '(1 2) 1) '((1) (2)))
(check-expect (comb '(1 2 3) 2) '((1 2) (1 3) (2 3)))

Before next lab

Lab 6

Before the lab


Questions

Time
5 Minutes
Activity
Group discussion / Announcments

Setup

Introducing foldr

Time
25 minutes
Activity
Small groups
Summary
foldr, functional_abstraction, contracts
(define (Foldr combine base lst)
  (cond
    [(empty? lst) base]
    [else (combine
            (first lst)
            (Foldr combine base (rest lst)))]))

Guess the function

Time
25 minutes
Activity
Individual work
Summary
foldr, functional_abstraction, lists

This part of the lab is based on FICS Exercise 29

Fill in the two instances of ... in the following template with a builtin function so that the tests pass. Try some other values for mylist, mylist1, mylist2 to help you guess.

#lang htdp/isl+
(define mylist '(1 2 buckle my shoe))
(check-expect (foldr cons empty mylist) (... mylist))
(define mylist1 '(3 4 5))
(define mylist2 '(1 2))
(check-expect (foldr cons mylist1 mylist2) (... mylist2 mylist1))

Filter in terms of foldr

Time
40 minutes
Activity
Individual work
Summary
foldr, functional_abstraction, lists

On your own, complete FICS Exercise 28

(check-expect (Filter (lambda (x) #f) '(1 2 3)) '())

(check-expect (Filter odd? '(0 1 2 3 4 5 6 7 8 9))
              (list 1 3 5 7 9))

Before next lab

No lab: Truth and Reconciliation Day
Lab 7 / Racket Quiz

Racket Quiz

The first half of the lab will be T1.


Background

Getting started

Questions

Time
5 Minutes
Activity
Group discussion / Announcments

Running JavaScript

Time
15 minutes
Activity
Demo

In a file

    console.log("Hello world");

Running a script

In a Browser

Note
Examples involving "prompt" and "alert" will only work in a browser.

In the REPL

JavaScript equality and type coercion

Time
10 Minutes
Activity
Demo

From Eloquent JavaScript Chapter 1, and the WAT talk by Gary Bernhardt, we know that type coercion is an important part of evaluating JS expressions. This is sometimes useful

> 42 + 'is a big number'

But just as often a source of errors and confusion.

> "" + 1
> x=""
> x++

One operator where type coercion can be particularly surprising is the standard equality test ==. Not only does type coercion apply:

> "" == 0
> false == 0
> "" == 0

but special rules apply to "undefined" and "null"

> false == undefined
> undefined == null
> undefined == undefined

even though they would normally be considered falsy (considered false in boolean contexts).

   > if (undefined) { console.log("truthy") } else { console.log("falsey") }

NaN is another falsy value not == to the other falsy values, not even itself:

   > NaN == undefined
   > NaN == NaN

To avoid this twisty maze of "helpful" type coercion, you can use the "strict equality" checker ===

   > "" === 0
   > false === 0
   > "" === 0
   > false === undefined
   > undefined === null
   > undefined === undefined

Javascript functions

Time
20 minutes
Activity
Individual

Reference for this section is JavaScript functions Like Racket, JavaScript has two different ways of defining functions. The first way is by assigning an anonymous function to a variable.

    (define square (lambda (x) (* x x)))
    let square = x => x*x;
    let square2 = function (x) {return x*x};

The more compact way of defining functions in both Racket and JavaScript combines the binding and creation of a function/lambda

    (define (square x) (* x x))
    function square(x) { return x*x }
const plus = (a,b) => {
    for (let i=0; i < a; i++){
        b++;
    }
    return b;
}

const mult = function (a,b) {
    sum=0;



    return sum;
}

Before the next lab

Lab 8

Before the Lab


Getting started

Node test runner

Time
10 Minutes
Activity
Demo

In order to provide similar functionality to check-expect in racket, we will use the nodejs test framework.

In order to use the test runner, we need to add two lines to the beginning of our javascript files.

const test=require("node:test");
const assert=require("assert");

We'll talk more about both const and require later.

A test is considered to pass if it does not throw an exception. assert provides several functions useful for this kind of test. We will concentrate on assert.strictEqual for now, which corresponds to the === test discussed in L07.

Here is a complete example with one passing test and one failing one

const test=require("node:test");
const assert=require("assert");

function add1(n) {
    return n+1;
}

test('one plus one is two', (t)=>assert.strictEqual(add1(1),2));
test('one plus one is three', (t)=>assert.strictEqual(add1(1),3));

Test coverage

We will use an experimental feature of node v20 in order to make sure we have test coverage (analogous to how we set up DrRacket for visual test coverage).

Getting a coverage report

Time
15 minutes
Activity
Group activity
ℹ start of coverage report
ℹ ---------------------------------------------------------
ℹ file      | line % | branch % | funcs % | uncovered lin…
ℹ ---------------------------------------------------------
ℹ sample.js | 100.00 |   100.00 |  100.00 |
ℹ ---------------------------------------------------------
ℹ all files | 100.00 |   100.00 |  100.00 |
ℹ ---------------------------------------------------------
ℹ end of coverage report

Writing tests

Time
25 minutes
Activity
Individual

Deep Comparison

Time
40 minutes
Activity
Exercise from book

Follow the Deep Comparison Exercise to write a function deepEqual that passes the following tests. assert uses something very similar for the deepStrictEqual test used below. Your function should pass the following tests.

let obj = {here: {is: "an"}, object: 2};
test("self", (t)=> assert.strictEqual(deepEqual(obj,obj),true));
test("null", (t)=> assert.strictEqual(deepEqual(null,null),true));
test("!null", (t)=> assert.strictEqual(deepEqual(null,obj),false));
test("different", (t)=>
    assert.strictEqual(deepEqual(obj, {here: 1, object: 2}),false));
test("equivalent", (t)=>
    assert.strictEqual(deepEqual(obj, {here: {is: "an"}, object: 2}),true));

Remember from above that you need the following lines to use the test framework

const test=require("node:test");
const assert=require("assert");

It can be frustrating trying to achieve full branch coverage (with our current tools). One useful trick is to turn one sided ifs into two sided ones, so the missing branch is turned into a missing line.

Before the next lab

No lab: Thanksgiving Day
Lab 09

Before the lab

Questions

Time
5 Minutes
Activity
Group discussion / Announcments

Getting started


JavaScript Arrays

JavaScript supports arrays. They are actually implemented as objects, which leads to some slightly surprising behaviour:

> x=[]
> x[10]=1
> x
> x["bob"] = 2
> x

Generating arrays

Time
10 minutes
Activity
Group programming / demo

Follow the (first part of the) Sum of a Range Exercise to write a range function that passes the following tests.

test("empty", (t)=>assert.deepStrictEqual(range(2,1),[]));
test("single", (t)=> assert.deepStrictEqual(range(2,2),[2]));
test("multiple", (t)=>
    assert.deepStrictEqual(range(42,50),[42,43,44,45,46,47,48,49,50]));

Arrays Continued

Time
20 minutes
Activity
Exercise from book

Follow the (second part of the) Sum of a Range Exercise to write a sum function that passes the following tests.

test("empty", (t)=> assert.strictEqual(sum([]),0));
test("single", (t)=> assert.strictEqual(sum([2]),2));
test("multiple", (t)=> assert.strictEqual(sum(range(1,10)),55));

Adding step argument to range.

Time
20 minutes
Activity
Individual

Add an optional step argument to the range function so that the following tests pass. The original tests should keep passsing, that's a big part of the point of having unit tests.

test("step 2", (t)=> assert.deepStrictEqual(range(1,10,2),[1,3,5,7,9]));
test("step -1", (t)=> assert.deepStrictEqual(range(5,2,-1),[5,4,3,2]));

Flattening

Time
25 minutes
Activity
Exercise from book.

Solve the Flatten Exercise using reduce and concat methods. Your solution should pass the following test suite.

test("base case", ()=> assert.deepStrictEqual(flatten([]),[]))
test("single element",
     function () {
     assert.deepStrictEqual(flatten([1]),[1]);
     assert.deepStrictEqual(flatten(["foo"]),["foo"]);
     assert.deepStrictEqual(flatten([{foo: 1}]),[{foo: 1}]);
     });
test("longer list", ()=>
    assert.deepStrictEqual(flatten([[1],2,[3],4,[5,6]]),[1,2,3,4,5,6]));

Does the following test pass with your implementation? If not, why not?

test("deeper nesting", (t)=>
    assert.deepStrictEqual(flatten([[[1],2,[3]],4,[5,6]]),[1,2,3,4,5,6]));

Here is a question for you to think about:

Every

Time
25 minutes
Activity
Exercise from book.

Solve the Every Exercise

Call the version using a loop every_loop

test("all true", (t)=>
    assert.strictEqual(every_loop([1, 3, 5], n => n < 10), true));
test("last false", (t)=>
    assert.strictEqual(every_loop([2, 4, 16], n => n < 10), false));
test("last middle false", (t)=>
    assert.strictEqual(every_loop([2, 16, 3], n => n < 10), false));
test("empty list", (t)=>
    assert.strictEqual(every_loop([], n => n < 10),true));

Call the version using the some method every_some. The tricky part here is to construct a function that is the negation of the given function.

test("all true", (t)=>
    assert.strictEqual(every_some([1, 3, 5], n => n < 10), true));
test("last false", (t)=>
    assert.strictEqual(every_some([2, 4, 16], n => n < 10), false));
test("last middle false", (t)=>
    assert.strictEqual(every_some([2, 16, 3], n => n < 10), false));
test("empty list", (t)=>
    assert.strictEqual(every_some([], n => n < 10),true));

Before next lab

Lab 10

Before the lab

Questions

Time
5 Minutes
Activity
Group discussion / Announcments

A Vector class

Time
25 minutes
Activity
Exercise from book.

Do the Vector Type exercise.

test("addition", (t) =>
    assert.deepStrictEqual(new Vec(1, 2).plus(new Vec(2, 3)),
                           new Vec(3,5)));
test("subtraction", (t)=>
    assert.deepStrictEqual(new Vec(1, 2).minus(new Vec(2, 3)),
                           new Vec(-1,-1)));
test("length", (t) =>
    assert.strictEqual(new Vec(3, 4).length,5));

A Set ("Group") class

Time
25 minutes
Activity
Exercise from book.

Do the Group exercise. Instead of the suggested array, use an object to store the elements of the "Group". The simplest way to implement from is to loop over the iterable argument and repeatedly call add.

const test=require("node:test");
const assert=require("assert");
class Group {
    constructor() {
        this.elements={}
    }
    add(element) {
        this.elements[element]=true;
    }
    has(element) {
    }
    delete(element) {
    }
    static from(iterable) {
    }
}
let group = Group.from([10, 20]);
test("has yes",(t)=>assert.strictEqual(group.has(10),true));
test("has no",(t)=>assert.strictEqual(group.has(30),false));
test("add existing is not error", (t)=>group.add(10));
test("delete existing", (t) => {
    group.delete(10);
    assert.strictEqual(group.has(10),false);
});

Timing functions

Time
40 minutes
Activity
Individual work.

We are presented with two different implementations of the Fibonacci function, and we want to see which one is faster 1.

const test=require("node:test");
const assert=require("assert");

function fib(n) {
    if (n<=2)
        return 1;
    else
        return fib(n-1)+fib(n-2);
}

let cache = {};
function memfib(n) {
    if (cache[n] !== undefined)
        return cache[n];

    if (n<=2)
        cache[n] = 1;
    else
        cache[n] = memfib(n-1)+memfib(n-2);

    return cache[n];
}

test("fib(35)=9227465",(t)=>assert.strictEqual(fib(35),9227465));
test("memfib(35)=9227465",(t)=>assert.strictEqual(memfib(35),9227465));

Using the function noisy as a template, write the higher order function timed that uses the builtins console.time and console.timeEnd to output timing information. The wrapped function produced by timed should produce the same values as the original function, as shown by the following tests.

test("timed(fib)(35)=9227465", (t)=>assert.strictEqual(timed(fib)(35),9227465));
test("timed(memfib)(35)=9227465",(t)=>assert.strictEqual(timed(memfib)(35),9227465));

let out=timed(fib)(42);
let out2=timed(memfib)(42);

test("fib(42)≈memfib(42)",assert.ok(Math.abs(out-out2)<0.000001))

It turns out that memfib is much faster. On my computer, the output from the last two timed calls is

fib(42): 970.887ms
memfib(42): 0.034ms

Notice how I have included the name of the function and the parameter in the output. Try to do the same.

Before Next Lab


  1. There are much faster ways to compute Fibonacci numbers↩
Lab 11

Before the lab


Getting started

Symbols

Time
10 minutes
Activity
Demo

You might remember symbols from Racket. It turns out JavaScript has something similar (but more confusing). Just like strings, Symbols can be used as keys (e.g. method names for objects). Here we rely on a predefined value to be able to call a method. In the next part of the lab, you will use the global Symbol.iterator as a method name.

const test=require("node:test");
const assert=require("assert");

let sym=Symbol("my cool symbol name");

test("uniqueness",
     (t)=>assert.notEqual(sym, Symbol("my cool symbol name")));

class Thing {
    constructor() {
        this.count=0;
    }
    // note the syntax to define indirect method names
    [sym]() {
        return this.count++;
    }
}

test("call",
     (t)=> {
         let x = new Thing();
         assert.strictEqual(x[sym](),0);
         assert.strictEqual(x[sym](),1);
     });

Iterable class

Time
40 minutes
Activity
Exercise from book.

Do the Iterable Group exercise.

Start by adding the following two methods to your Group class.

    // Utility function for iterator class
    keys() {
        return Object.keys(this.elements);
    }
    // Mark this class as iterable.
    [Symbol.iterator]() {
        return new GroupIterator(this);
    }

Next create a GroupIterator class.

class GroupIterator {
    constructor(group) {
        this.index=0;
        this.group=group;
    }
    next() {
    }
}

Refer to the MatrixIterator class for inspiration, but note that you should always return an object with a value property. When you are done, the following test should pass.

test("iterate", (t) => {
    let vals=[];
    for (let value of Group.from(["a", "b", "c"])) {
        vals.push(value+value);
    }
    assert.deepStrictEqual(vals,["aa","bb","cc"]);
});

Methods without classes

Time
10 minutes
Activity
Demo

We can use JavaScript objects in a simple way by e.g. naming conventions for functions.

function timePlus(time1, time2) {
    let mins = (time1.mins + time2.mins) % 60;
    let hours = time1.hours + time2.hours + Math.floor((time1.mins+time2.mins)/60);
    return {'hours': hours, 'mins': mins};
}

console.log(timePlus({hours: 10, mins:30}, {hours: 17, mins:47}));

If we want to have "time" objects with a "plus" method, one way is to add that method manually. In order for that to work, we need to make use of the JavaScript variable this. When the function method is called as object.method(), the special variable this is defined to mean the current object. We can use this to wrap our existing function as a method.

function maketime(hours, mins){
    let plus=function (other) {
        let raw=timePlus(this,other);
        return ______________________________
    };

    return { 'hours': hours, 'mins': mins, 'plus': plus};
}

let A=maketime(10, 30);
let B=maketime(17, 47);
let C=A.plus(B);
test("A+B=C",(t)=>assert.ok(C.hours===28 && C.mins===17 && typeof(C.plus)=='function'));

Protypes

Time
20 minutes
Activity
Individual work

Adding methods manually to newly created objects is a bit confusing and verbose, so JavaScript has the notion of a 'prototype',

let protoTime = {
    plus: function(other) {
        let raw=timePlus(this,other);
        return timeNew(raw.hours, raw.mins);
    }
};

In the following code, the method plus is inherited from the prototype, but the fields hours and minutes are not. Fill in the blanks to get the following code working.

function timeNew(hours, mins) {
    let obj=Object.create(protoTime);
    _______________;
    _____________;
    return obj;
}

D=timeNew(21,42);
E=timeNew(17,37);

F=D.plus(E);
test("D+E=F",(t)=>assert.deepEqual(F,{hours: 39, mins:19}));

The benefit is not huge here, but you can see how it would help if there were many methods, all creating new objects.

Classes (are really about prototypes)

Time
20 minutes
Activity
Individual work

In practice it's not usual to call object.create directly with the prototype object, but rather to use new keyword, along with the prototype property of a constructor.

function Time(hours, mins){
    this.hours=hours;
    this.mins=mins;
}

Time.prototype.plus=function (other) {
    let raw=timePlus(this,other);
    return ______________________________;
}

G = new Time(20,59);
H = new Time(11,11);

I=G.plus(H);
test("G+H=I (raw)",(t)=>assert.notDeepStrictEqual(I,{hours: 32, mins:10}));
test("G+H=I (constructor)", (t)=>assert.deepStrictEqual(I, new Time(32,10)));

As we saw already, modern javascript provides the class keyword to concisely generate constructors and prototypes.

class Time2 {
    constructor(hours, mins){
        this.hours=hours;
        this.mins=mins;
    };
    plus(other) {
        let raw=timePlus(this,other);
        ______________________________________;
    }
}

Time2;

J= new Time2(5,30);
K= new Time2(11,55);

L=J.plus(K); 
test("J+K=L (raw)",(t)=>assert.notDeepStrictEqual(L,{hours: 17, mins:25}));
test("J+K=L (wrong constructor)", (t)=>assert.notDeepStrictEqual(L, new Time(17,25)));
test("J+K=L (right constructor)", (t)=>assert.deepStrictEqual(L, new Time2(17,25)));

It's important to know that this is just convenience syntax for the same prototype based system.

Before next lab

Read the followings sections from Chapter 11 of Eloquent Javascript:

From the MDN JavaScript Guide, read Using Promises

Lab 12

Before the lab

Read the followings sections from Chapter 11 of Eloquent Javascript:

From the MDN JavaScript Guide, read Using Promises

Background

Callback Chaining

Time
25 minutes
Activity
Code puzzle.

The recommended way to get maximimum performance from the node.js filesystem API is to use callbacks, i.e. functions to call when the I/O operation completes.

Replace the ALL-CAPITALS words in the following code sample with defined identifiers to make this callback chaining example work.

const fs=require("node:fs");

function log(string, next) {
    let date = new Date();
    function finish(err) {
        if (err) throw err;
        console.timeEnd("write");
        CALLBACK();
    }
    function write(err, fd) {
        if (err) throw err;
        fs.write(VALUE, date.toISOString() + ": " + string, CALLBACK);
    }
    console.time("write");
    fs.open("log.txt", "a", CALLBACK)
}

console.time("log");
log("first\n",
    () => {
        log("second\n",
            () => console.log("done"));
    });
console.timeEnd("log");

When you get the code working, the file log.txt should contain lines like the following (the exact date and time may differ):

2024-10-25T17:31:56.626Z: first
2024-10-25T17:31:56.629Z: second

Questions to think about:

Promises

Time
25 minutes
Activity
Code puzzle, reading documentation

In the Promises API file system methods return a Promise object that automates the chaining of callbacks. These Promise objects can be chained together using then. Fill in the appropriate API calls (they should be very similar to the first part, without the explicit callbacks).

const fs=require("node:fs/promises");

function log(string) {
    let date = new Date();
    return new Promise(next=> {
        console.time("write");
        API_CALL
            .then(fd=>API_CALL)
            .then(()=>console.timeEnd("write"))
            .then(CALLBACK)
            .catch((err) => console.log(err));
    });
}

console.time("log");
log("first\n")
    .then(()=>log("second\n"))
    .catch((err) => console.log(err));
console.timeEnd("log");

Questions to think about:


Async Functions

Time
25 minutes
Activity
Code puzzle, reading book

Async Functions provide some nice features for programming with Promises, essentially eliminating some of the boilerplate from our previous example. They also introduce one very important keyword.

Replace the ALL-CAPITALS parts of the following program to duplicate the functionality of the previous versions.

const fs=require("node:fs/promises");

async function log(string) {
    console.time("write")
    const fd = MAGIC_KEYWORD API_CALL()
    let date = new Date();

    const promise=API_CALL();
    console.timeEnd("write");
    return promise;
}

console.time("log");
log("first\n")
    .then(()=>log("second\n"))
    .catch((err) => console.log(err));
console.timeEnd("log");

Before Next Lab

Lab 13 / JS Quiz

Before the lab


JS Quiz

The first half of the lab will be a JavaScript quiz.


Getting Started

Hello Python

Time
10 Minutes
Activity
Demo

Let's do Exercise 1.1 and 1.2 together

Mortgage Calculator

Time
20 Minutes
Activity
Modify given program

Do exercises 1.7 and 1.8 from Python Numbers

Introduction to Python strings

Time
20 Minutes
Activity
Experiment in Python REPL

Do exercises 1.13, 1.14, 1.15 from Python Strings

Lab 14

Before the Lab

Questions

Time
5 Minutes
Activity
Group discussion

Getting Started

- Download Work.zip and unzip in your newly created directory.

Pytest

Time
10 minutes
Activity
Demo
symbols = 'HPQ,AAPL,IBM,MSFT,YHOO,DOA,GOOG'
symlist = symbols.split(',')

def test_lookup0():
    assert symlist[0] == 'HPQ'

def test_lookup1():
    assert symlist[1] == 'AAPL'
[student@id414m22 L14]$ pytest listex.py
=================== test session starts ===================
platform linux -- Python 3.9.18, pytest-7.4.3, pluggy-1.3.0
rootdir: /home1/ugrad/student/cs2613/labs/L14
plugins: pylama-8.4.1, cov-4.1.0
collected 2 items

listex.py ..                                        [100%]

==================== 2 passed in 0.02s ====================

Lists and Pytest

Time
20 minutes
Activity
Individual programming from template

Functions and coverage

Time
20 minutes
Activity
Individual programming, modify previous solution

We have already been using python functions for pytest, without really thinking about how they work. In Part 1.7 of Practical Python, functions are explained.

def sumcount(n):
    '''
    Returns the sum of the first n integers
    '''
    total = 0
    while n > 0:
        total += n
        n -= 1
    return total

Files

Time
20 minutes
Activity
Individual programming, synthesis

Data types

Tuples

Time
20 minutes
Activity
Individual programming, synthesis

Before next lab

Lab 15

Before the Lab


Getting Started

Dictionaries

Time
20 minutes
Activity
Individual programming, synthesis
def test_cost():
    d = parse_row(row)
    cost = compute_cost (d)
    assert cost == pytest.approx(3220.000,abs=0.00000001)

def test_d():
    d = parse_row(row)
    update_dict(d)
    assert d == {'name': 'AA', 'shares': 75, 'price':32.2, 'date': (6, 11, 2007),
                 'account': 12345}

Containers: read_portfolio

Time
20 minutes
Activity
Write function based on template
def test_read():
    portfolio = read_portfolio('Data/portfolio.csv')
    assert portfolio == \
        [('AA', 100, 32.2), ('IBM', 50, 91.1),
         ('CAT', 150, 83.44), ('MSFT', 200, 51.23),
         ('GE', 95, 40.37), ('MSFT', 50, 65.1), ('IBM', 100, 70.44)]

def test_total():
    portfolio = read_portfolio('Data/portfolio.csv')
    total = 0.0
    for name, shares, price in portfolio:
        total += shares*price
    assert total == pytest.approx(44671.15,abs=0.001)

Time
20 minutes
Activity
Modify results of previous exercise
def test_read():
    portfolio = read_portfolio('Data/portfolio.csv')
    assert portfolio == \
        [{'name': 'AA', 'shares': 100, 'price': 32.2}, {'name': 'IBM', 'shares': 50, 'price': 91.1},
         {'name': 'CAT', 'shares': 150, 'price': 83.44}, {'name': 'MSFT', 'shares': 200, 'price': 51.23},
         {'name': 'GE', 'shares': 95, 'price': 40.37}, {'name': 'MSFT', 'shares': 50, 'price': 65.1},
         {'name': 'IBM', 'shares': 100, 'price': 70.44}]

def test_total():
    portfolio = read_portfolio('Data/portfolio.csv')

    total = 0.0
    for s in portfolio:
        total += s['shares']*s['price']
    assert total == pytest.approx(44671.15,abs=0.001)

Sequences

Time
25 minutes
Activity
Convert REPL session to tests
def test_items():
    assert prices.items() == \
        [('GOOG', 490.1), ('AA', 23.45), ('IBM', 91.1), ('MSFT', 34.23)]
- Question: what is `list()` being used for in this section?
- Embed the following tests and make sure they pass
def test_zip():
    assert pricelist == \
        [(490.1, 'GOOG'), (23.45, 'AA'), (91.1, 'IBM'), (34.23, 'MSFT')]

def test_min_max():
    assert min(pricelist) == (23.45, 'AA')
    assert max(pricelist) == (490.1, 'GOOG')

No lab: Reading Week
No lab: Reading Week
Lab 16

Before the Lab


Getting Started

List Comprehensions

Time
25 minutes
Activity
Write tests based on REPL session
import pytest
from report2 import read_portfolio
prices = {
        'GOOG' : 490.1,
        'AA' : 23.45,
        'CAT': 35.46,
        'IBM' : 91.1,
        'MSFT' : 34.23,
        'GE': 13.48,
    }

Note that the value test will need to be adjusted for a value of approximately 31167.10, since our price list is different from the one used in the book.

Higher order functions

Time
20 minutes
Activity
Assemble given pieces
def test_portfolio():
    portfolio = parse_csv('Data/portfolio.csv', types=[str, int, float])
    assert portfolio == [{'price': 32.2, 'name': 'AA', 'shares': 100},
                         {'price': 91.1, 'name': 'IBM', 'shares': 50},
                         {'price': 83.44, 'name': 'CAT', 'shares': 150},
                         {'price': 51.23, 'name': 'MSFT', 'shares': 200},
                         {'price': 40.37, 'name': 'GE', 'shares': 95},
                         {'price': 65.1, 'name': 'MSFT', 'shares': 50},
                         {'price': 70.44, 'name': 'IBM', 'shares': 100}]

def test_shares():
    shares_held = parse_csv('Data/portfolio.csv', select=['name', 'shares'], types=[str, int])
    assert shares_held == [{'name': 'AA', 'shares': 100}, {'name': 'IBM', 'shares': 50},
                           {'name': 'CAT', 'shares': 150}, {'name': 'MSFT', 'shares': 200},
                           {'name': 'GE', 'shares': 95}, {'name': 'MSFT', 'shares': 50},
                           {'name': 'IBM', 'shares': 100}]

Refactoring a function

Time
30 minutes
Activity
Refactor function to add feature
def test_tuple():
    prices = parse_csv('Data/prices.csv', types=[str,float], has_headers=False)
    assert prices == [('AA', 9.22), ('AXP', 24.85), ('BA', 44.85), ('BAC', 11.27),
                      ('C', 3.72), ('CAT', 35.46), ('CVX', 66.67), ('DD', 28.47),
                      ('DIS', 24.22), ('GE', 13.48), ('GM', 0.75), ('HD', 23.16),
                      ('HPQ', 34.35), ('IBM', 106.28), ('INTC', 15.72), ('JNJ', 55.16),
                      ('JPM', 36.9), ('KFT', 26.11), ('KO', 49.16), ('MCD', 58.99),
                      ('MMM', 57.1), ('MRK', 27.58), ('MSFT', 20.89), ('PFE', 15.19),
                      ('PG', 51.94), ('T', 24.79), ('UTX', 52.61), ('VZ', 29.26),
                      ('WMT', 49.74), ('XOM', 69.35)]

Raising exceptions

Time
20 minutes
Activity
Add error check
def test_exception():
    with pytest.raises(RuntimeError) as e_info:
        prices = parse_csv('Data/prices.csv', select=['name','price'], has_headers=False)
Lab 17

Before the Lab


Getting started


Questions

Time
10 minutes
Activity
Q&A

Modules

Time
20 minutes
Activity
Refactor existing code to to reuse a function.
def test_prices():
    portfolio = read_portfolio('Data/portfolio.csv')

    prices = {  s['name']: s['price'] for s in portfolio }
    assert prices['AA'] == pytest.approx(32.2,abs=0.001)
    assert prices['GE'] == pytest.approx(40.37,abs=0.001)

Methods

Time
20 minutes
Activity
Write accessor and mutator methods.

def test_cost2():
    s = Stock('GOOG', 100, 490.10)
    assert s.cost() == pytest.approx(49010.0,0.001)

def test_sell():
    s = Stock('GOOG', 100, 490.10)
    s.sell(25)
    assert s.shares == 75
    assert s.cost() == pytest.approx(36757.5, 0.001)

Special Methods

Time
25 minutes
Activity
Code to test, learn about "dunder" methods.
def test_repr():
    goog = Stock('GOOG', 100, 490.1)
    assert repr(goog) == "Stock('GOOG', 100, 490.1)"

Tables

Time
25 minutes
Activity
Code to test, learn about "dunder" methods.

Write a Python class Table whose constructor takes a list of strings selecting columns, and a list of dictionaries corresponding to rows. You should support the str function by implementing the appropriate "dunder" method. Your method should return a string of the formatted table with the given columns selected.

  def make_abm():
      return [{'name': 'Alice', 'hobby': 'Kendo', 'age': 21},
              {'name': 'Bob', 'hobby': 'Skiing', 'age': 23},
              {'name': 'Mallory', 'hobby': 'Cryptanalysis', 'age': 30}]

  def test_strings():
      rows=make_abm()
      table = Table(['name', 'hobby'], rows)
      assert str(table) == \
          'name      hobby     \n' + \
          'Alice     Kendo     \n'+ \
          'Bob       Skiing    \n' + \
          'Mallory   Cryptanalysis'

  def test_strings_numbers():
      rows=make_abm()
      table = Table(['name', 'age'], rows)
      assert str(table) == \
          'name      age       \n' + \
          'Alice     21        \n'+ \
          'Bob       23        \n'+ \
          'Mallory   30        '

Before next lab

Study for the Python Quiz

Lab 18 / Python Quiz

Before the Lab

Study for the Python Quiz

Quiz

Time
50 minutes
Activity
Quiz

The first half of the lab will be a Python quiz


Getting started

Hello Go

Time
10 minutes
Activity
Demo
// Our first program will print the classic "hello world"
// message. Here's the full source code.
package main

import "fmt"

func main() {
    fmt.Println("hello world")
}

Running go code is a bit more complicated than the other languages we studied so far.

# To run the program, put the code in `hello-world.go` and
# use `go run`.
$ go run hello-world.go
hello world

# Sometimes we'll want to build our programs into
# binaries. We can do this using `go build`.
$ go build hello-world.go
$ ls
hello-world hello-world.go

# We can then execute the built binary directly.
$ ./hello-world
hello world

# Now that we can run and build basic Go programs, let's
# learn more about the language.

Loops

Time
20 minutes
Activity
Modify given example
// `for` is Go's only looping construct. Here are
// some basic types of `for` loops.

package main

import "fmt"

func main() {

    // The most basic type, with a single condition.
    i := 1
    for i <= 3 {
        fmt.Println(i)
        i = i + 1
    }

    // A classic initial/condition/after `for` loop.
    for j := 0; j < 3; j++ {
        fmt.Println(j)
    }

    // Another way of accomplishing the basic "do this
    // N times" iteration is `range` over an integer.
    for i := range 3 {
        fmt.Println("range", i)
    }

    // `for` without a condition will loop repeatedly
    // until you `break` out of the loop or `return` from
    // the enclosing function.
    for {
        fmt.Println("loop")
        break
    }

    // You can also `continue` to the next iteration of
    // the loop.
    for n := range 6 {
        if n%2 == 0 {
            continue
        }
        fmt.Println(n)
    }
}

Modify the above example so that the output of each loop is reversed. For those involving range, modify the Println statement.

% go run for.go
3
2
1
3
2
1
range 2
range 1
range 0
loop
5
3
1

Conditionals

Time
20 minutes
Activity
Synthesize program
// Branching with `if` and `else` in Go is
// straight-forward.

package main

import "fmt"

func main() {

    // Here's a basic example.
    if 7%2 == 0 {
        fmt.Println("7 is even")
    } else {
        fmt.Println("7 is odd")
    }

    // You can have an `if` statement without an else.
    if 8%4 == 0 {
        fmt.Println("8 is divisible by 4")
    }

    // Logical operators like `&&` and `||` are often
    // useful in conditions.
    if 8%2 == 0 || 7%2 == 0 {
        fmt.Println("either 8 or 7 are even")
    }

    // A statement can precede conditionals; any variables
    // declared in this statement are available in the current
    // and all subsequent branches.
    if num := 9; num < 0 {
        fmt.Println(num, "is negative")
    } else if num < 10 {
        fmt.Println(num, "has 1 digit")
    } else {
        fmt.Println(num, "has multiple digits")
    }
}

// Note that you don't need parentheses around conditions
// in Go, but that the braces are required.

Use the example above, along with a for loop, to write the "Fizzbuzz" example

% go run fizz-buzz.go
Fizzbuzz
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Fizzbuzz
16
17
Fizz
19
Lab 19

Before the Lab

Getting started

Functions

Time
25 minutes
Activity
Complete given example
package main

import "fmt"

// Here's a function that takes two `int`s and returns
// their sum as an `int`.
func plus(a int, b int) int {
    // fill in a recursive definition of plus in the style of Lab 2

}

// When you have multiple consecutive parameters of
// the same type, you may omit the type name for the
// like-typed parameters up to the final parameter that
// declares the type.
func plusPlus(a, b, c int) int {
    return plus(plus(a, b),c)
}

func main() {

    // Call a function just as you'd expect, with
    // `name(args)`.
    res := plus(1, 2)
    fmt.Println("1+2 =", res)

    res = plusPlus(1, 2, 3)
    fmt.Println("1+2+3 =", res)
}
$ go run functions.go 
1+2 = 3
1+2+3 = 6
$ go run functions.go
1+2 = 3
7-3 = 4
1+2+3 = 6

Pointers

Time
25 minutes
Activity
Extend given example
// Go supports <em><a href="https://en.wikipedia.org/wiki/Pointer_(computer_programming)">pointers</a></em>,
// allowing you to pass references to values and records
// within your program.

package main

import "fmt"

// We'll show how pointers work in contrast to values with
// 2 functions: `zeroval` and `zeroptr`. `zeroval` has an
// `int` parameter, so arguments will be passed to it by
// value. `zeroval` will get a copy of `ival` distinct
// from the one in the calling function.
func zeroval(ival int) {
    ival = 0
}

// `zeroptr` in contrast has an `*int` parameter, meaning
// that it takes an `int` pointer. The `*iptr` code in the
// function body then _dereferences_ the pointer from its
// memory address to the current value at that address.
// Assigning a value to a dereferenced pointer changes the
// value at the referenced address.
func zeroptr(iptr *int) {
    *iptr = 0
}

func main() {
    i := 1
    fmt.Println("initial:", i)

    zeroval(i)
    fmt.Println("zeroval:", i)

    // The `&i` syntax gives the memory address of `i`,
    // i.e. a pointer to `i`.
    zeroptr(&i)
    fmt.Println("zeroptr:", i)

    // Pointers can be printed too.
    fmt.Println("pointer:", &i)

    // A new pointer to a value can be created with the
    // builtin function `new`.
    p := new(42)
    fmt.Println("value at *p:", *p)
    zeroptr(p)
    fmt.Println("value at *p:", *p)
}

    *p=3
    i=4
    swapint(&i,p)
    fmt.Println("after swap value at *p:", *p)
    fmt.Println("after swap value in i", i)
$ go run pointers.go
initial: 1
zeroval: 1
zeroptr: 0
pointer: 0x344372b720f8
value at *p: 42
value at *p: 0
after swap value at *p: 4
after swap value in i: 3

Structs

Time
20 minutes
Activity
Modify given example
// Go's _structs_ are typed collections of fields.
// They're useful for grouping data together to form
// records.

package main

import "fmt"

// This `person` struct type has `name` and `age` fields.
type person struct {
    name string
    age  int
}

// `newPerson` constructs a new person struct with the given name.
func newPerson(name string) *person {
    // Go is a garbage collected language; you can safely
    // return a pointer to a local variable - it will only
    // be cleaned up by the garbage collector when there
    // are no active references to it.
    p := person{name: name}
    p.age = 42
    return &p
}

func main() {

    // This syntax creates a new struct.
    fmt.Println(person{"Bob", 20})

    // You can name the fields when initializing a struct.
    fmt.Println(person{name: "Alice", age: 30})

    // Omitted fields will be zero-valued.
    fmt.Println(person{name: "Fred"})

    // An `&` prefix yields a pointer to the struct.
    fmt.Println(&person{name: "Ann", age: 40})

    // It's idiomatic to encapsulate new struct creation in constructor functions
    fmt.Println(newPerson("Jon"))

    // Access struct fields with a dot.
    s := person{name: "Sean", age: 50}
    fmt.Println(s.name)

    // Structs are mutable.
    s.age = 51
    fmt.Println(s)

    // You can also use dots with struct pointers - the
    // pointers are automatically dereferenced.
    sp := &s
    sp.age = 52
    fmt.Println(sp.age)

    // If a struct type is only used for a single value, we don't
    // have to give it a name. The value can have an anonymous
    // struct type. This technique is commonly used for
    // [table-driven tests](testing-and-benchmarking).
    dog := struct {
        name   string
        isGood bool
    }{
        "Rex",
        true,
    }
    fmt.Println(dog)
}

go run structs.go
{Bob 20 1}
{Alice 30 3}
{Fred 0 7}
&{Ann 40 2}
&{Jon 42 1}
Sean
{Sean 51 6}
52
{Rex true}

Tests (and modules)

Run example tests

Time
10 minutes
Activity
demo
package intutils

func IntMin(a, b int) int {
    if a < b {
        return a
    }
    return b
}
package intutils

import (
    "fmt"
    "testing"
)

func TestIntMinBasic(t *testing.T) {
    ans := IntMin(2, -2)
    if ans != -2 {

        t.Errorf("IntMin(2, -2) = %d; want -2", ans)
    }
}

func TestIntMinTableDriven(t *testing.T) {
    var tests = []struct {
        a, b int
        want int
    }{
        {0, 1, 0},
        {1, 0, 0},
        {2, -2, -2},
        {0, -1, -1},
        {-1, 0, -1},
    }

    for _, tt := range tests {

        testname := fmt.Sprintf("%d,%d", tt.a, tt.b)
        t.Run(testname, func(t *testing.T) {
            ans := IntMin(tt.a, tt.b)
            if ans != tt.want {
                t.Errorf("got %d, want %d", ans, tt.want)
            }
        })
    }
}

func BenchmarkIntMin(b *testing.B) {
    for b.Loop() {

        IntMin(1, 2)
    }
}
# Setup a module
$ cd ~/cs2613/labs/L19/intutils
$ go mod init example.com/intutils
# Run all tests in the current project in verbose mode.
$ go test -v
== RUN   TestIntMinBasic
--- PASS: TestIntMinBasic (0.00s)
=== RUN   TestIntMinTableDriven
=== RUN   TestIntMinTableDriven/0,1
=== RUN   TestIntMinTableDriven/1,0
=== RUN   TestIntMinTableDriven/2,-2
=== RUN   TestIntMinTableDriven/0,-1
=== RUN   TestIntMinTableDriven/-1,0
--- PASS: TestIntMinTableDriven (0.00s)
    --- PASS: TestIntMinTableDriven/0,1 (0.00s)
    --- PASS: TestIntMinTableDriven/1,0 (0.00s)
    --- PASS: TestIntMinTableDriven/2,-2 (0.00s)
    --- PASS: TestIntMinTableDriven/0,-1 (0.00s)
    --- PASS: TestIntMinTableDriven/-1,0 (0.00s)
PASS
ok      examples/testing-and-benchmarking   0.023s

# Run all benchmarks in the current project. All tests
# are run prior to benchmarks. The `bench` flag filters
# benchmark function names with a regexp.
$ go test -bench=.
goos: linux
goarch: amd64
pkg: example.com/main
cpu: 12th Gen Intel(R) Core(TM) i7-12700
BenchmarkIntMin-20      1000000000           0.4362 ns/op
PASS
ok      examples.com/main   0.439s

Test coverage

Time
20 minutes
Activity
Extend code and add matching tests
% go test -cover
PASS
coverage: 50.0% of statements
ok      example.com/intutils    0.002s
Lab 20
Lab 21
Lab 22
Lab 23