Search code examples
sml

Comparing strings using the 'compare' function


To compare two strings and add the string to a list if they're equal, I created this function using the built-in compare function:

fun compareString(string, list) = 
    if compare(string, "hello") = EQUAL then string::list;

However, this gives an error. I guess my syntax must be wrong, did I use the compare function correctly?

According to the documentation, the compare function works as follows:

compare (s, t) does a lexicographic comparison of the two strings using the ordering Char.compare on the characters. It returns LESS, EQUAL, or GREATER, if s is less than, equal to, or greater than t, respectively.


Solution

    • What you are forgetting is the else ... part of if-then-else. This part is mandatory.

    • You probably want to use the function String.compare specifically.

    • If you only care about the equal case, though, you could simply use the = operator.

    • The name compareString is a weird name for a function that conses a string to a list.

    • The names string and list are also not very good variable names, because they don't describe the purpose of the variables. If the function is generic, then generic names might be appropriate, and you can pick whatever scheme of generic names you like.

    • The inclusion predicate (that a string must be equal to "hello") seems a little silly, since you will know exactly how that list is going to look like; it will be isomorphic to a positive integer. If, instead, you made the inclusion predicate into a parameter, the function might actually be useful.

    For example:

    fun consIf (p, x, xs) =
        if p x
        then x :: xs
        else xs
    
    fun is_greeting x = List.exists (fn y => x = y) ["hello", "hi", "good day"]
    val ys = consIf (is_greeting, "hello", ["hi"])
    

    Or make this into a binary operator and name it ::? because it resembles :: with a condition:

    infixr 5 ::?
    fun x ::? xs = fn p => if p x then x::xs else xs
    
    val ys = ("boaty mcboatface!" ::? ["hi"]) is_greeting