Standard ML: Getting Last in List

1k views Asked by At

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

2

There are 2 answers

1
Aadit M Shah On BEST ANSWER

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.

1
Connor Smith On

The idiomatic way would be either just to allow the function to fail on invalid inputs:

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

Or to use an option type:

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

This also works for any generic list, not only those of ints.