Search code examples
haskellrecursionfunctional-programming

Recursive Functional Programming Question not making sense


The question is:

    FunctionZ [] = 0
    FunctionZ[x:xs] = x + 2 * FunctionZ(xs)

Complete the table below by writing the value of the argument passed to each call of

    FunctionZ

and the value returned by each call, when

    FunctionZ [4,2,5,3]

is evaluated.

Then there is a table to fill in

Call number Argument Value Returned
1 [4,2,5,3]
2
3
4
5

Any help is much appreciated. I’ve never done this at university etc. I understand the concepts of heads and tails but that’s about it.

The answers for the problem are below, however I would like to know how to get to the answer through step by step instructions:

Call number Argument Value Returned
1 [4,2,5,3] 52
2 [2,5,3] 24
3 [5,3] 11
4 [3] 8
5 [0] 3

Thanks

I have tried to expand the callable brackets.


Solution

  • The equations

    functionZ [] = 0
    functionZ (x:xs) = x + 2 * functionZ xs
    

    effectively construct a definition by cases. They are equivalent to: (pseudo code)

    functionZ list =
      if list is empty
      then the result is zero
      else if list starts with x (head) and continues with xs (tail)
      then the result is x + 2 * functionZ(xs)
      else runtime error: "unhandled case"
    

    Note that the last branch ("unhandled case") is never actually taken since your equations cover all possible cases: we call that exhaustive pattern matching. I've included it to be general.

    Key aspects:

    • The left-hand-side of an equation like functionZ (x:xs) = ... performs two tasks: it checks if the input list is of that form (i.e., non empty), and simultaneously binds the head and tail of the input list to variables x and xs. This pattern-matching is much better than using functions like head list since (exhaustive) pattern matches never crashes, while head list can crash if list is empty.

    • The equations are tried in order, top to bottom. Here it's irrelevant, since there is no overlapping case between the two equations, but that's not always the case.

    So, you start with functionZ [4,2,5,3] and apply the second equation. That defines x = 4 and xs = [2,5,3], and then performs the recursive call.

    functionZ [2,5,3] also falls within the case of the second equation. That defines x = 2 and xs = [5,3], and then performs the recursive call.

    You should be able to continue until the empty list, after which you have to compute the result of each intermediate call and fill the table, from bottom to top.