Search code examples
smlml

remove last element of a list sml by keeping the list in a val


How can I remove the last element in a list in Standard ML? I have a list defined as:

val list = [1, 4, 6, 8, 9]

and I want to remove the last element and have the list in the val list.


Solution

  • Well you have various ways of doing it.

    • You could take the original list apart, and start building a new list with the elements, until you reach the last element.

      fun f [] = ...
        | f [x] = ...
        | f (x::xs) = x :: ...
      
    • Or you could use the List.take function to take the first i elements from the list. Obviously you could use the List.length function to calculate how many elements you wan't to take from the list.

      fun h xs = List.take (xs, ...)