Home > database >  Can't access the value of int in a double list sml
Can't access the value of int in a double list sml

Time:11-16

I cant access the value of int*int inside a double list

fun fnd(xs:(int*int)list list)=
    if null xs
    then 0
    else #2 xs

example i input

fnd [[(1,2)]];

i want to print the second value which is 2

CodePudding user response:

The value you are passing to fnd is a list of lists of tuples. You appear to wish to get the second value from the first tuples in the first list. This is best accomplished with pattern matching.

fun fnd([[(_, x)]]) = x
  | _ = 0

The second pattern _ matches any value that wasn't previously matched.

Notte that this is not an especially useful way to return. What if the list passed in is [[(1, 0)]]. This would return 0 as well and the caller of this function would not know which had happened: was the list empty, or did it find the value?

Returning an option type would convey that.

fun fnd([[(_, x)]]) = SOME x
  | _ = NONE
  • Related