【问题标题】:Handle variables not in datatype处理不在数据类型中的变量
【发布时间】:2017-03-09 02:55:47
【问题描述】:

我希望完成的是将字符串和布尔值传递到列表中。 'switch' 运算符切换输入类型的前两个元素,'and' 运算符和前两个元素。

但是,如果我想“和”一个布尔值和一个字符串,我该如何向列表中添加一个错误字符串(“错误”)?此外,SMl 不接受 x::y::xs 我应该输入什么,因为无论类型如何,我都想切换。

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

任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: sml smlnj


    【解决方案1】:

    and 是关键字,因此您将bin_op 更改为switch | and_opx::y::zs 是完全有效的 sml。在辅助函数stack 的第一行中没有定义。最后,在 sml 中将两个布尔值“和”在一起的关键字是 andalso

    这是编译的代码:

    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
    

    存在不匹配的模式,但我假设您要么将它们排除在外,要么稍后再加入。

    【讨论】:

    • 感谢您的回复,现在对我来说很有意义。
    【解决方案2】:

    听起来您正在为动态类型构建一个解释器 语。如果这是真的,我会区分抽象语法 你的程序和解释器的错误处理,不管 是否使用异常或值来指示错误。例如,

    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)
    

    【讨论】:

    • 感谢您的回复,这与我看到的口译员所做的类似。
    猜你喜欢
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 2021-09-25
    • 2018-08-12
    • 2019-05-04
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多