【问题标题】:Function expects list when it should be expecting a string函数在期望字符串时期望列表
【发布时间】:2021-05-20 21:04:01
【问题描述】:
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 ("Gender", "Female", studentTable)

Ocaml 向我抛出异常:

第 1 行,字符 13-21: 错误:此表达式具有字符串类型,但表达式应为类型 '一个列表

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

【问题讨论】:

  • 尝试添加一些类型注释。这将大大缩小可能的原因。
  • 在restrictionRows 中,您将attribute 与[] 匹配,因此它是ocaml 的列表。在restriction 中,您将"Gender" 传递为attribute,然后在需要列表的restrictionRows 中使用。

标签: ocaml


【解决方案1】:

类型检查器 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 设置编辑器也很有用,这样当您不同意类型检查器时,您可以查询函数的类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    相关资源
    最近更新 更多