the reason for the error is because this line:
contains l1 l2 = starts l1 l2;
is no different from the previous line:
contains l1 (hd::tl) = contains l1 tl
Both lines express an identical matching pattern. You can see this as you can write: contains l1 (l2 as (hd::tl)) = contains l1 tl
This will confuse the interpreter as you are telling it that in the case of this pattern: contains l1 l2
, do two different things, namely:
starts l1 l2;
and
contains l1 tl
The way to get to your solution here is to eliminate the last line of contains
as it is redundant.
In the second line your purpose is to now loop over the initial elements of the second list until you get to a point where the 'current element' of the second list matches the first element of the first list. If this is the case, then invoke start
else continue looping.
Consider val first_list = [2,3,4]
and val second_list = [1,2,2,2,2,3,4,5,6]
So contains
in the second line will have to first loop over the elements of the second_list
to see if the first elements match. If they match then invoke start. So you get following breakdown:
2=1? => false
thus loop to second element
2=2? => true
thus invoke start
to see if we have a matching list from then onwards.
As start
will return false the moment it checks 3=2? => false
, you now have to continue looping in contains
and repeat this procedure. It will have to loop until it reaches the final 2
in second_list
. At this point the comparison will be like this:
2=2? => true
thus invoke start
to check to see if the consecutive elements match.
start
will now evaluate to true
as follows:
3=3? => true
4=4? => true
5=5? => true
--> At this point start
will return true which should be the return value of contains as well. If start
at any point returns false
then you need to continue looping.
Eventually you will pattern match first_list
with []
which will be caught by your first line.
NOTE:
start
is correct but avoid this pattern: if a=b then true else false
, instead just write a=b
:
So rewrite last line of start
like this:
| starts (h1::t1) (h2::t2) = ((h1=h2) andalso (starts t1 t2));