Search code examples
listfunctional-programmingsmlsmlnj

Standard ML : Searching a list of tuples


I'm trying to write a function in SML that searches a list of tuples for a string and if it finds the string in the first element of the tuple, it returns the second.

fun getFromBlist (name : command, (x,y)::tail : (command*command) list) = 
    if x = name then y else getFromBlist(name, tail)
    | getFromBlist(name, []) = ***** WHAT GOES HERE?!? *****

Is there anything that I can use for the base case that will just return nothing? Everything I try, I get an error. I'm open to other suggestions here as well, thanks.


Solution

  • You can use the Option structure to return NONE for the base case, I've slightly reformatted the code, putting the base case first,

    As well as returning SOME y for a match, and NONE for the base case. From there you can use a case statement, or pattern matching to retrieve the result.

    type command = string;
    
    fun getFromBlist(name, []) = NONE
      | getFromBlist (name : command, (x,y)::tail : (command*command) list) =
        if x = name
          then SOME y
          else getFromBlist(name, tail);
    

    Alternatively, depending on what you want, for the base case you could return the empty string "", and return y as you did originally. It kind of depends on if the empty string is a valid command, and you want to differentiate between that and the base case.

    But to summarize the base case, and the result of then must return the same type, be it string, or option