【问题标题】:How to construct a correct type transformation in OCaml?如何在 OCaml 中构造正确的类型转换?
【发布时间】:2022-01-05 18:37:25
【问题描述】:

为了从构造类型tainted_value映射到其他类型,从其他基本类型映射到构造类型tainted_value,构造了两个函数。

首先,类型tainted_value定义为:

type object_ = int 
and location = Obj of object_ | Null
and closure = var * cmd * stack
and value = Fld of string | Int of int | Loc of location | Clo of closure
and tainted_value = Val of value | Error

如果我只是让我的第一个函数从 tainted_value 映射到 string 看起来像:

let tva_to_string tva1 = match tva1 with 
  | Val (Fld e) -> e 
  | _ -> None

它报告错误为:

This expression has type 'a option but an expression was expected of type string

但是,如果我将None 更改为failwith "Empty",它不会返回错误:

let tva_to_string tva1 = match tva1 with
  | Val (Fld e) -> e 
  | _ -> failwith "Empty"

为什么?

【问题讨论】:

    标签: ocaml


    【解决方案1】:

    Noneoption 类型的构造函数。如果match 中的一个子句返回None,那么其他子句必须返回option 类型的其他值。它们也可能引发异常,这就是 failwith 函数所做的。

    option 的另一个构造函数是Some,所以您可能正在寻找:

    let tva_to_string tva1 = match tva1 with 
      | Val (Fld e) -> Some e 
      | _ -> None
    

    这将缓解您的类型检查问题。当然,它仍然没有返回string,所以你对函数的命名要么需要做一些工作,要么需要返回字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-03
      • 2016-08-29
      • 2012-09-22
      • 2016-10-06
      • 2013-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多