对称关系递归SML
在 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);
我只能检查前两个元素的对称性,但我需要检查其余的。
Define a recursive predicate in ML isRelationSymmetric that accepts a relation r (represented as a list of tuples) and returns true if r is symmetric and false otherwise.
Here is what I have so far.
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);
I was only able to check for symmetry for the first two elements but I need to check the rest.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于 @jwolf 似乎已经解决了这个问题,因此有一种利用
List.exists
的替代方法。但是,为了澄清,应该
[(1, 2), (2, 1), (2, 3), (3, 2), (3, 2)]
测试对称或不对称,因为有两个(3, 2)
实例,而只有 1 个(2, 3)
实例?如果我们想抓住这一点,我们可以使用 List.filter 来查找我们正在考虑的对的任何反向,然后计算该列表的长度。该列表的长度应等于与当前匹配的对列表的长度。
As @jwolf appears to have solved this, an alternative approach taking advantage of
List.exists
.However, for clarification, should
[(1, 2), (2, 1), (2, 3), (3, 2), (3, 2)]
test as symmetric, or not, as there are two instances of(3, 2)
and only 1 of(2, 3)
?If we want to catch this, we can use
List.filter
to find any reverses of the pair we're considering, and then calculate the length of that list. The length of that list should be equal to the length of the list of pairs matching the current one.