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.