微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

类型与列表操作不匹配

如何解决类型与列表操作不匹配

Ocaml 中的新功能,我正在尝试实现几个函数来管理自定义类型列表。

我正在尝试管理一个类型列表,当我需要向列表中添加一个新元素时,我需要进行一些检查。 这是我的实际代码

open Ast
open Easy_logging
exception DuplicateEntry

let logger = Logging.make_logger "SymbolTable" Debug [Cli Debug]

type variable = {
  id: string;
  tipe: Ast.typ
}

type dec = {
  variables: variable list;
  parent: dec option
}

let begin_block table =
  if List.length table > 1 then
     let last_scope = List.nth table ((List.length table) -1) in
     let new_scope = {variables=[]; parent=last_scope} in
     new_scope::table
  else {variables=[]; parent=None}::table

let add_entry symbol info table =
  let tail_scope = List.nth table ((List.length table) - 1) in
  {id=symbol; tipe=info}::tail_scope.variables;
  logger#debug "Added inside the table the node with id %s" symbol

let rec lookup symbol table = failwith "lookup: Not implemented yet"

我正在尝试执行 begin_block 操作,但出现以下错误

File "src/symbol_table.ml",line 31,characters 16-21:
31 |      new_scope::table
                     ^^^^^
Error: This expression has type dec option list
       but an expression was expected of type dec list
       Type dec option is not compatible with type dec 
Command exited with code 2.
Compilation unsuccessful after building 26 targets (0 cached) in 00:00:01.

在这种情况下,表是列表 我丢失了一些东西,但目前我无法找到错误:/,也许这是一个愚蠢的问题。

解决方法

您在这里省略了很多上下文,为了重现,我不得不删除对缺失模块的引用,这意味着我做出了一些可能是错误的假设。

鉴于此,我的猜测是您复制了最初使用 Base 或 Core 标准库替换的代码,其中 List.nth 函数返回 'a option,而不是标准 OCaml 实现如果给定的索引超出范围,则会引发异常。

我这么认为的原因是 parentdec 字段的类型为 dec option 并且直接分配了 last_scope,这意味着 last_scope 必须具有同类型。如果 List.nth 的类型为 'a list -> int -> 'a,那么 'a 的类型必须为 dec option,这意味着 table 的类型必须为 dec option list。并且您不能在 dec 前面添加 dec option list,因此会出现错误。

最后,找到此类问题的原因的一个好方法是通过注释变量类型来明确您的假设。例如,在这里注释 table 的类型会给你一个不同的错误,缩小它 last_scope 具有类型 dec 但在分配时预计具有类型 dec optionparent

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。