Search code examples
recursionsml

Standard ML: Getting Last in List


I'm trying to get the last element of a list of integers in SML but I want to indicate (somehow) when the user passes in an unacceptable list (such as an empty one). My code is here:

fun lastInList [] = ~1
    | lastInList [x] = x
    | lastInList (x::xs) =
    lastInList xs;

This works on any non-empty list since execution will always hit the second line before the first. However, is there an idiomatic way of being able to deal with all integers? I'd like to return some kind of exception, I guess. Current solution isn't great because -1 can be in my list (obviously).

Thanks for the help, bclayman


Solution

  • You can always raise an exception:

    fun last []      = raise Empty
      | last (x::xs) = last' x xs
    
    fun last' x []      = x
      | last' _ (x::xs) = last' x xs
    

    Another option (if you would pardon the pun):

    fun last []      = NONE
      | last (x::xs) = SOME (last' x xs)
    
    fun last' x []      = x
      | last' _ (x::xs) = last' x xs
    

    Hope that helps.