【问题标题】:Submatrix Ocaml子矩阵 Ocaml
【发布时间】:2017-09-10 01:43:30
【问题描述】:
    let moja_matrika1 = [[1; 2]; [3; 4]];;
let moja_matrika2 = [[4; 7; 8]; [3; 2; 1]];;

let rec does_it_contain (lis1, lis2) =
if (List.hd lis1 = []) then false
else if (List.hd lis1 = lis2) then true
else does_it_contain ((List.tl lis1), lis2);;

let rec does_it (matrix, lis1) =
if (matrix = []) then false
else if does_it_contain (List.hd matrix, List.hd lis1) = true then true
else does_it (List.tl matrix, lis1);;

does_it (moja_matrika1, moja_matrika2);;

我正在尝试检查一个矩阵是否是另一个矩阵的 sbumatrix。但我必须使用类型列表列表。而且我不能使用任何定义的 List 函数。显然我正在使用 List hd,tl 但我会替换它。

当我尝试调用我不理解的函数时出现错误。

   does_it (moja_matrika1, moja_matrika2);;
Error: This expression has type int list list
       but an expression was expected of type 'a list list list
       Type int is not compatible with type 'a list # 

请帮忙!

【问题讨论】:

  • "但我必须使用类型列表列表":如果你这样做是为了学习以外的任何其他事情,你不应该使用列表来表示矩阵,这是非常低效的。
  • 我知道,这是给学校的。

标签: matrix ocaml submatrix


【解决方案1】:

dos_it_contain 和dos_it 的签名分别是:

  'a list list * 'a list -> bool 
  'a list list list * 'a list list -> bool  

它们都不能将 2 个矩阵作为参数('a list'a list list list 不是您期望的矩阵)

此外,您编写函数的代码就像它是 C 或 java 一样:参数不能通过 Ocaml 中的括号传递。括号用于元组 - 在这种情况下没有用。

【讨论】:

  • 所以,它没用,还是?对不起,我是 Ocaml 的初学者。我编写了 Delphi、Java、C。但 Ocaml 只是别的东西。我似乎无法绕过它。关于如何改进此代码,使其工作的任何建议,如果可能的话?谢谢我
  • 首先,它没用。但它也给你的代码增加了一些惩罚,因为它创建了另一个数据结构(元组),你可以对其进行解构以处理每个元素。在更大的代码上,它会增加时间复杂度 - 甚至可能是大矩阵代码的情况。
【解决方案2】:

我想通了。

let rec does_it_contain (lis1, lis2) =
    if rep lis1 = [] then false
    else if rep lis2 = [] then false
  else if (  glava lis1 = glava lis2) then true
 else does_it_contain ( lis1, rep lis2);;

let rec does_it (matrica, matrica1) =
    if rep matrica = [] then false
    else if rep matrica1 = [] then false
    else if does_it_contain ( glava matrica, glava matrica1) = true then true
    else  does_it ( rep matrica,  rep matrica1);;


does_it(moja_matrika1, moja_matrika2);;

rep 是 List.tl 的替代品,glava 是 List.hd 的替代品。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    相关资源
    最近更新 更多