0

Define a function which, given a list L, an object x, and a positive integer k, returns the position of the k-th occurrence of x in L if x appears at least k times in L otherwise 0. For example, if L is [#"a", #"b", #"c", #"b"], x is #"b", and k is 2, then the function returns 4.

For this problem, I can't use any auxiliary functions and can't use the length function. Any ideas on how I would go about solving it?

  • 4
    Practice by writing a function that returns the position of the first occurrence, if there is one. Then expand on that idea. – molbdnilo Sep 23 '13 at 07:07

1 Answers1

2

Assume find is the function you have to implement. Two things are immediate from the description:

  • find returns an integer
  • find takes at least three arguments (L, x, and k)

Furthermore, functions on lists typically distinguish between two cases: either the given list is empty ([]) or it contains at least one element (y::ys). Thus we can use the following skeleton for find

fun find   []    x k = ...
  | find (y::ys) x k = ...

You should start by thinking about what to do in either case. If L is empty there are definitely no occurrences of x in it, thus the result is 0. Otherwise, L consists of a head-element y and the remaining list ys. If x is equal to y, we just found an occurrence of x, otherwise we have to continue to search in ys. According to this, the skeleton can be refined into

fun find   []    x k = 0
  | find (y::ys) x k =
      if x = y then ...
      else find ys x k

At this point the only remaining part is when L is not empty and x = y. But since we are interested in the k-th occurrence of x, we have to check whether we found it or not. This could be done by decreasing k each time we find an occurrence of x and finally, when we find an occurrence and k is 1 at the same time, we found the desired k-th occurrence of x.

fun find   []    x k = 0
  | find (y::ys) x k =
       if x = y andalso k > 1 then find ys x (k - 1)
       else if x = y then ...
       else find ys x k

The remaining case is that we found the k-th occurrence of x. So we should return the index i of this occurrence. But where should we get i from? In some way we have to compute it inside our function. How to do this, is for you to find out.

chris
  • 4,988
  • 20
  • 36