Reputation: 712
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.
Upvotes: 2
Views: 141
Reputation: 16105
It sounds like you're building an interpreter for a dynamically typed language. If that is true, I would distinguish between the abstract syntax of your program and the error handling of the interpreter, regardless of whether you use exceptions or values to indicate error. For example,
datatype value = Int of int
| Bool of bool
| String of string
datatype exp = Plus of Exp * Exp
| And of Exp * Exp
| Concat of Exp * Exp
| Literal of value
exception TypeError of value * value
fun eval (Plus (e1, e2)) = (case (eval e1, eval e2) of
(Int i, Int j) => Int (i+j)
| bogus => raise TypeError bogus)
| eval (And (e1, e2)) = (case eval e1 of
Bool a => if a
then ...
else ...
| bogus => ...)
| eval (Concat (e1, e2)) = (case (eval e1, eval e2) of
(String s, String t) => String (s^t)
| bogus => raise TypeError bogus)
Upvotes: 1
Reputation: 3558
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.
Upvotes: 4