I am currently working on a ML small project and learning how to work with it, but here are some problems that I'm facing but cannot find any source online.
I want to have a function to return the last number of the list, which is a real number list. I wrote a code to return a single element real list, but i will it to be a real number but not a list. here is my code:
fun last [] = nil
| last(head::nil) = [head]
| last(head::list) = last(list)
I thought
last(head::nil)=head
would help get the real number but it just give me an error that:
operator domain: 'Z list list
operand: real list
Thank you!
As melpomene says, nil
isn't a value of type real, so it can't be the return type for the empty list. In fact, no value can be returned, because the list is empty! This makes the function last
partial. You want to avoid partial functions, because they may crash at runtime. You can define an alternative function, lastOpt
:
fun lastOpt [] = NONE
| lastOpt [x] = SOME x
| lastOpt (_::xs) = lastOpt xs
For example,
- lastOpt [1,2,3];
> val it = SOME 3 : int option
- lastOpt [];
> val it = NONE : 'a option
This passes responsibility for handling empty lists explicitly to the caller of lastOpt
.
The built-in function List.last
was made unsafely with exceptions:
fun last [] = raise Empty
| last [x] = x
| last (_::xs) = last xs
I wouldn't recommend using this.