Search code examples
smlsmlnj

Handle variables not in datatype


What I wish to accomplish is to pass strings and booleans into a list. The 'switch' operator switches the first two elements of type input, the 'and' operator ands the first two elements.

However, how would I add an error string to the list ("error") if I wanted to 'and' a boolean and a string? Also, SMl does not accept x::y::xs what should I put instead since I would like to switch regardless of type.

datatype input = Bool_value of bool | String_Value of string | Exp_value of string
datatype bin_op = switch | and

fun helper(switch, x::y::xs) = y::x::stack 
    |   helper(and, Bool_value(x)::Bool_value(y)::xs) = Bool_value(x and y)::xs

Any help will be appreciated, thank you.


Solution

  • and is a keyword, so you change the bin_op to switch | and_op. x::y::zs is perfectly valid sml. In the first line of the helper function stack is not defined. Finally, the keyword to "and" two booleans together in sml is andalso.

    Here is code that compiles:

    datatype input = Bool_value of bool | String_Value of string | Exp_value of string
    datatype bin_op = switch | and_op
    
    fun helper(switch, x::y::xs) = y::x::xs 
    | helper(and_op, Bool_value(x)::Bool_value(y)::xs) = Bool_value(x andalso y)::xs
    

    There are unmatched patterns, but I assume you either left them out or will put them in later.