Skip to content

Latest commit

 

History

History
70 lines (56 loc) · 1.62 KB

File metadata and controls

70 lines (56 loc) · 1.62 KB

1. sum is a function which takes a slice of numbers and adds them together. What would its function signature look like in Go?

sum(nums []int) int

2. Write a function which takes an integer and halves it and returns true if it was even or false if it was odd. For example half(1) should return (0, false) and half(2) should return (1, true).

func half(i int) (int, bool) {
    return i / 2, i % 2 == 0
}

3. Write a function with one variadic parameter that finds the greates number in a list of numbers.

func greatest(args ...int) int {
    max := args[0]

    for _, v := range args {
	    if v > max {
		    max = v
		}
	}
	
	return max
}

4. Using makeEvenGenerator as an example, write a makeOddGenerator function that generates odd numbers.

func makeOddGenerator() func() uint {
    i := uint(1)
    return func() (ret uint) {
        ret = i 
        i += 2 
        return 
    }
}

5. The Fibonacci sequence is defined as: fib(0) = 0, fib(1) = 1, fib(n) = fib(n-1) + fib(n-2). Write a recursive function which can find fib(n).

func fib(n int) int {
    if n == 0 {
	    return 0
	} else if n == 1 {
		return 1
	} else {
	    return fib(n - 1) + fib (n - 2)
	}
}

6. What are defer, panic and recover? How do you recover from a run-time panic?

defer schedules a function call to be run after the completion of the function
panic immediately stops the execution of the function
recover stops the panic and returns the value that was passed to the call to panic

We can recover from a run-time panic using the recover built-in.