在 ML isRelationSymmetric 中定義一個遞回謂詞,它接受關系 r(表示為元組串列),如果 r 是對稱的,則回傳 true,否則回傳 false。
這是我到目前為止所擁有的。
fun isRelationSymmetric([]) = false
| isRelationSymmetric((a,b)::rest) =
val x = [(1,2),(2,1),(2,3),(3,2)]; //suppose to come out true
val y = [(1,1),(1,3)]; //suppose to come out false
val z = [(1,2),(2,1),(1,3)]; //suppose to come out false
isRelationSymmetric(x);
isRelationSymmetric(y);
isRelationSymmetric(z);
我只能檢查前兩個元素的對稱性,但我需要檢查其余部分。
uj5u.com熱心網友回復:
fun isRelationSymmetric(relation) =
let
fun testOne((a, b), []) = false
| testOne((a, b), (c, d)::rest) =
(b = c) andalso (a = d) orelse testOne((a, b), rest);
fun test([]) = true
| test((a,b)::rest) = testOne((a, b), relation) andalso test(rest);
in
test(relation)
end;
(* Test cases *)
val x = [(1, 2), (2, 1), (2, 3), (3, 2)]; (* true *)
isRelationSymmetric(x);
val y = [(1, 1), (2, 3)]; (* false *)
isRelationSymmetric(y);
val z = [(1, 2), (2, 1)]; (* true *)
isRelationSymmetric(z);
uj5u.com熱心網友回復:
正如@jwolf 似乎已經解決了這個問題,一種利用List.exists.
fun sym(relation) =
let
fun sym'([]) = true
| sym'((a, b)::rest) =
List.exists (fn (c, d) => a = d andalso b = c) relation
andalso sym'(rest)
in
sym'(relation)
end;
但是,為了澄清起見,是否應該[(1, 2), (2, 1), (2, 3), (3, 2), (3, 2)]測驗為對稱的,因為有兩個實體(3, 2)且只有 1 個(2, 3)?
如果我們想抓住這一點,我們可以用它List.filter來找到我們正在考慮的對的任何反向,然后計算該串列的長度。該串列的長度應等于與當前配對的配對串列的長度。
fun sym(relation) =
let
fun sym'([]) = true
| sym'((a, b)::rest) =
let
val len = List.length(List.filter (fn (c, d) => a = d andalso b = c) relation)
val len' = List.length(List.filter (fn (c, d) => a = c andalso b = d) relation)
in
len = len' andalso sym'(rest)
end
in
sym'(relation)
end;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/455706.html
