ocaml - OCaml 编译类型错误,不是正确的预期函数类型
问题描述
OCaml 的新手在这里。
基本上试图用两个函数编译一段代码,但我无法在第 9 行,第 26-27 列字符的类型错误中编译它,说:
“错误:此表达式的类型为 t,但表达式应为字符串类型”
基本上,第 8 行调用的解析函数需要类型字符串,但我不知道为什么。
sexp 参数的类型:
type sexp = Atom of string | List of sexp list
代码:
open Sexplib.Sexp
let rec parse_bindings bindings =
match bindings with
| [] -> []
| first::rest ->
match first with
| List([Atom(name); e]) ->
[(name, parse e)] @ (parse_bindings rest)
let rec parse sexp : expr =
match sexp with
| Atom(s) ->
(* some code *)
| List(sexps) ->
match sexps with
| (* some code *)
| [Atom("let"); List(bindings_sexp); e2] ->
let binding_expr = parse_bindings bindings in
ELet(binding_expr, parse e2)
| _ -> failwith "foo"
解决方案
您提供的代码不会编译,因为parse
在第 9 行引用,但直到稍后才定义。
要定义两个相互递归的函数,您需要使用let rec ... and ...
:
let rec f x = (* definition of f, which calls g *)
and g x = (* definition of g, which calls f *)
由于后面的定义parse
在第 9 行是不可见的,所以名称必须引用一些以前的定义。也许模块parse
中定义了一个名为的函数。Sexp
(这是open
谨慎使用的原因之一。)
推荐阅读
- android - 如何将单击的按钮上的文本传递给另一个 Activity?
- javascript - Blogger 上的引导导航栏 - 如何设置
- php - 如何在php中洗牌
- node.js - Mongo 从对象数组聚合 $or 和 $match
- java - 如何创建自定义键盘以默认用于应用程序中的所有输入?
- c - 如何使用 Wininet 向服务器发送二进制 (.zip) 文件
- reactjs - 在 React Native 中在哪里添加 .d.ts 文件
- django - 如何在django中定义一个直接指向静态文件的URL?
- string - 字符串比较:equalsIgnoreCase 失败但 == 通过
- java - Java - 使用通配符创建数组列表