函数在它应该期待一个字符串时期待列表

Function expects list when it should be expecting a string

type table = string * string list * string list list;;

let studentTable = ("Student",
                    ["ID";"Name";"Gender";"Course"],
                    [["2";"Jim";"Male";"Geography"];
                     ["4";"Linnea";"Female";"Economics"];
                     ["7";"Steve";"Male";"Informatics"];
                     ["9";"Hannah";"Female";"Geography"]]);;

let rec restrictMatch(attribute,value,attributeList,dataList) =
  match (attribute,value,attributeList,dataList) with
    ([],_,_,_) -> false
  | (_,[],_,_) -> false
  | (_,_,[],_) -> false
  | (_,_,_,[]) -> false
  | ((wh::wt),value,(ah::at),(h::t)) ->
      if wh=ah && value=h
      then true
      else restrictMatch(attribute,value,at,t)

          
let rec restrictRows(attribute,value,attributeList,dataList) =
  match (attributeList,dataList) with 
    (_,[]) -> []
  | ([],_) -> []
  | ((ah::at),(h::t)) ->
      if restrictMatch(attribute,value,attributeList,h)
      then h::restrictRows(attribute,value,attributeList,t)
      else restrictRows(attribute,value,attributeList,t)

          
let restriction (attribute,value,table) =
  match table with 
    (name,attributeList,dataList)->
      (attributeList,restrictRows(attribute,value,attributeList,dataList))

我正在尝试使用 OCaml 实现 'restriction' 的关系代数函数。但是,当我尝试 运行 'restriction' 函数时:

restriction ("Gender", "Female", studentTable)

Ocaml 向我抛出异常:

Line 1, characters 13-21: Error: This expression has type string but an expression was expected of type 'a list

但是,这对我来说没有意义,因为我 99% 确定我没有在代码中的任何地方传递列表。

类型检查器 100% 确定您正在使用 attribute 作为列表。 事实上,您正在将 attribute 与空列表进行比较:

let rec restrictMatch(attribute,value,attributeList,dataList) =
  match (attribute,value,attributeList,dataList) with
  | [],_,_,_ -> false

旁白:

在首选柯里化函数的 OCaml 中,将元组用于函数不是惯用的:

let rec restrictMatch attribute value attributeList dataList = ...

同样,使用let-binding绑定元组更简单:

let name, attributeList, dataList = table in
...

而不是match table with

用 merlin 设置你的编辑器也很有用,这样当你不同意类型检查器时,你可以查询函数的类型。