Drills

Drills — write the functions

Functions have to be written, not just read. Five drills, from easy to harder — each one adds a little to the last. Write the function, call it from main on the examples, then compare with the solution. (We only have functions, if and basic types so far — no loops yet, and none of these need one.)

1 (easy) — square. One parameter in, one value out.

square(7) → 49
func square(n int) int {
    return n * n
}

2 (easy) — isEven. Return a bool straight from an expression — no if needed.

isEven(4) → true      isEven(5) → false
func isEven(n int) bool {
    return n%2 == 0
}

n%2 is the remainder after dividing by 2; == 0 turns it into a yes/no. Returning the comparison directly is idiomatic Go — don't write if ... { return true } else { return false }.

3 (medium) — absDiff. The distance between two numbers, always positive. Here a branch is needed.

absDiff(3, 8) → 5      absDiff(8, 3) → 5
func absDiff(a, b int) int {
    if a > b {
        return a - b
    }
    return b - a
}

4 (medium) — safeDiv. Return two values: the quotient and a bool saying whether it worked. Dividing by zero would crash, so guard it — this is the (value, ok) pattern from step 3.

safeDiv(20, 4) → 5, true      safeDiv(5, 0) → 0, false
func safeDiv(a, b int) (int, bool) {
    if b == 0 {
        return 0, false
    }
    return a / b, true
}

Call it with two variables: q, ok := safeDiv(20, 4). You'll meet this exact shape again in lesson 12 as (value, error).

5 (harder) — minMax. Return the smallest and the largest of three numbers — two returns, several comparisons.

minMax(7, 2, 5) → 2, 7
func minMax(a, b, c int) (int, int) {
    min, max := a, a
    if b < min {
        min = b
    }
    if c < min {
        min = c
    }
    if b > max {
        max = b
    }
    if c > max {
        max = c
    }
    return min, max
}

Tip — the copy trap (step 3). None of these change their arguments; they compute and return. That's on purpose: a function gets a copy of what you pass, so trying to "fix up" a parameter in place is silently lost. If a function must produce a changed value, return it — exactly like safeDiv and minMax do. These small pure functions are also the easiest kind to test automatically in lesson 13.