首页 > 解决方案 > 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"

标签: ocaml

解决方案


您提供的代码不会编译,因为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谨慎使用的原因之一。)


推荐阅读