Question:
Like the title says, I’m trying to see if two unordered lists include the same values and if these values appear the same amount of times in these lists. The assignment given asks not to order the lists. Here’s what I’ve done so far:- my logic was to compare recursively if the second list (from now on l2 ) includes the
hd
(= first element) of the first list ( from now on l1 ) if it does, compare thetl
of l1. And as long as I call thisisEqual
function I would remove the hd of l1 and the first position in which the same value appears in l2. My base case would be that the 2 lists have different lengths then I would know for sure they are not equal. Here’s the code:
Answer:
I think you’re overthinking this problem.Now, if neither of the lists are empty, then let’s pattern match that so that we can get to the head and tail of the first list.
x
from lst2
and run the same function recursively on xs
and what’s left of lst2
, we should be able to reduce down to a result.So let’s write a helper
remove
function. Your delete
is on the right track, but it’s reliant on an index, and indexes aren’t really a natural fit with lists.The
option
type is a good choice to represent a case where we try to remove a value that is not in a list. Getting NONE
would tell us pretty handily that the two are not equal.isEqual
.Of course, you could also just sort both lists, and then this becomes much more straightforward.
If you have better answer, please add a comment about this, thank you!