I’m having some troubles with this assignment. This is what the professor is asking for:
Write a function oldest that takes a list of dates and evaluates to an
(int*int*int)option. It evaluates to NONE if the list has no dates
and SOME d if the date d is the oldest date in the list.
I know how to create the function and have some idea on how to work with the list of dates, but I don’t know how to “store” the oldest value to compare it with the tail of the list of dates. This is what I submitted (it doesn’t work, it always retrieves the first date, but I would really love to know the answer)
fun oldest (datelist : (int * int * int) list) =
if null datelist
then NONE
else if null (tl datelist) then
SOME (hd datelist)
else let val date = if is_older (hd datelist, hd (tl datelist)) then SOME (hd datelist) else SOME (hd (tl datelist))
in oldest(tl datelist)
end
One way of keeping a value across recursive calls, is to pass it along in an argument. As you can’t change the original function, the most used solution is to have a helper function which takes this extra argument, and possible others as well.
Such a helper function could take the head of the list and compare it with the extra argument, using the oldest of the two in the recursive call on the tail of the list. Then when the list is empty, you just return this extra argument, as it must be the oldest.
Another solution could be to take out the two first elements of the list, putting back the oldest of the two, thus in each recursive call you remove one element of the list, and at some point there will only be one element in the list, which must be the oldest.