I am trying to get the oldest person from the list of records in SML. I have started as I would with a simple list:
type person = {age:int, name: string} list
val p:person = [{age=11, name="Marco"},{age=12, name="Polo"}]
fun maxAge [] = NONE
| maxAge [x] = SOME x
| maxAge (p1 :: p2 :: xs) = if #age(p1) > #age(p2) then
maxAge (p1 :: xs)
else
maxAge (p2 :: xs)
I get the following error:
Error: unresolved flex record
(can't tell what fields there are besides #age)
I thought p1 and p2 would be first and second elements of the list, in my case a record of name and age {age=11, name="Marco"}, and that I could easily access value by #age(p1) and then send the full record p1 deeper into the recursion, but that is not the case. Why?
Any tips would be highly appreciated.
PS: How can I print only the name string when I get the right record, this does not work:
maxAge [x] = SOME #name(x)
I found my answer in this question, the problem was that you can't pattern match "p1" and record, instead it has to be done like this:
...
maxAge ({age= p1, name= n1} :: {age= p2, name= n2} :: xs)
...
Then you can use "p1", "p2",... to proceed.