2017-04-13 40 views
0
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,但我会替换它。Submatrix Ocaml

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

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 # 

请帮忙!

+0

“_but我必须使用类型列表list_”: 如果你这样做的任何事情比学习别人,你不应该用列表来表示矩阵,这是非常低效的。 – ChriS

+0

我知道,这是为了学校。 – Broda

回答

0

我想通了。

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的替代品。

0

does_it_contain和does_it的签名是结构延续respectnot:

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

他们都不是能够拿2矩阵作为参数('a list'a list list list像您期望的不是矩阵)

而且,你把你的函数的代码写成如C或者java一样:参数不能通过Ocaml的圆括号传递。括号用于元组 - 在这种情况下这没有用。

+0

那么,它没用,或? 我很抱歉,我是Ocaml的初学者。我写了Delphi,Java,C,但Ocaml只是别的。我似乎无法把头围住它。 有关如何改进此代码的任何建议,使其工作,如果它是可行的? 谢谢 我 – Broda

+0

在第一位,它是无用的。但是它也会给你的代码增加一些代价,因为它会创建另一个数据结构(元组),以解构每个元素。在较大的代码中,它会增加时间复杂度 - 甚至可能会导致您的代码使用大矩阵。 –