I´m a newbie in SML and I´d like to update my function so that it has two outputs: a list AND 1 or 0. The function was proposed here: SML: Remove the entry from the List. It returns an updated list without a row that contains ´elem´.
fun removeElem elem myList = filter (fn x => x <> elem) myList
The function should return a new list AND 1, if a raw has been deleted. Otherwise, it should return an old list AND 0.
Any hint or example is highly appreciated. Thanks.
Note that all SML functions take a single input and return a single output. Instead, think of returning a tuple containing the new list and a flag indicating whether any elements were removed. One possibility is to use a couple of functions from the standard basis to test whether
elemis inmyListand build up a tuple consisting of that and the results from thefiltershown in the question. The test might look like:There are more concise ways to write that, but it shows the idea. Note that it returns a
boolinstead of anint; this is more precise, so I won’t convert to the integers requested in the question.A drawback of the above is that it requires traversing the list twice. To avoid that, consider the type that the function must return: a tuple of a list without
elemand a flag showing whether anyelems have been removed. We can then write a function that take a new value and a (valid) tuple, and returns a valid tuple. One possibility:We can then apply
updateto each element ofmyListone-by-one. Since we want the order of the list to stay the same, apart from the removed elements, we should work throughmyListfrom right to left, accumulating the results into an initially empty list. The functionfoldrwill do this directly:However, there is a lot of logic hidden in the
foldrhigher-order function.To use this as a learning exercise, I’d suggest using this problem to implement the function in a few ways:
foldlandfoldrUnderstanding the differences between these versions will shed a lot of light on how SML works. For each version, let the types guide you.