Find the middle element in an int list (SML/NJ)

The following is a function that I wrote as an assignment for my Language Design class that returns the middle element of an integer list.

fun middle lst = 
    fun reduceByTwo ([],onelst)  = hd(onelst) (*When our twolst is empty we are at the middle*)
    |   reduceByTwo (twolst,[]) = 0 (*This should never happen*)
    |   reduceByTwo (twolst, onelst) =
        if null twolst orelse null onelst then 0
            else if tl(twolst) = [] orelse tl(tl(twolst)) = [] then hd(onelst)
        if null lst then 0

The idea is that we send our helper function reduceByTwo, a tuple of lst and recurse until twolst is null. We reduce twolst by two elements every time so when it becomes null, that indicates we are at the halfway point of onelst and can simply return the head of onelst.

Example output:

- middle[1,5,1,214,1,14,1,24,100,99,41,2,4,4565,7,76,34];
val it = 100 : int

Leave a Reply

Your email address will not be published. Required fields are marked *