我有一个数据库表,我试图在OCaml中建模。但是,当我尝试编写提取列的函数时,我遇到了问题。我已经设法编写了一个只有一列表的函数,但是如果我有一个包含更多列的表,那么我就会遇到匹配失败。我需要帮助如何在我的模式匹配中表示我的表。
(* Table with many columns *)
let tableWithManyColumns =
"carTable",
[ ("RegNumber", ["1";"2";"3";"4"]);
("Brand", ["BMW";"SAAB";"Volvo";"Jeep"]);
("Year",["2000";"2003";"2001";"2012"]);
];;
(*Table with one columns*)
let tableWithOneColumn = "carTable",
[
("RegNumber", ["1";"2";"3";"4"])
];;
(*Current extractColumn*)
let extractColumn (t:string * (string * string list) list) =
match t with
(a,[(b,c)])-> b;;
(* Returns Regnumber *)
extractColumn(tableWithOneColumn);;
(*Returns match failure*)
extractColumn(tableWithManyColumns);;
模式[(b,c)]
与单对列表匹配。因此它将与[("hello", "world)]
匹配,但不会与[("hello", "world"); ("another", "pair")]
或[]
或任何长度不等于1的列表匹配。如果要匹配长度大于1的任何列表,则需要使用first :: rest
模式,其中first
将与列表的第一个元素匹配,rest
与列表的其余部分匹配(超出第一个元素的所有内容) 。
以下函数将提取第一列的名称,
type column = string * string list (* name, values *)
type base = string * column list (* tableName, columns *)
let firstColumnName : base -> string = fun table -> match table with
| (_tableName, (columnName,_values) :: _otherColumns) -> columnName
| _ -> failwith "wrong table representation"
例,
# firstColumnName tableWithOneColumn;;
- : string = "RegNumber"
# firstColumnName tableWithManyColumns;;
- : string = "RegNumber"