两个子句定义以查找列表上的最大数 [英] Two clause definition to find the maximum number on a list

查看:39
本文介绍了两个子句定义以查找列表上的最大数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何编写两个子句递归定义来查找列表中的最大值.到目前为止,我已经写了这个:

How would I write a two clause recursive definition to find the maximum value in a list. So far I have written this:

 max(L,M):-  

 max([H|T],M):-

max(T,H,M).
max([],M,M).
max([H|T],Y,M):-
   H =< Y,
   max(T,Y,M).
max([H|T],Y,M):-
   H > Y,
   max(T,H,M).

这不起作用,它说有一个我不太清楚的语法错误,而且我知道它也不是两个子句.有谁知道我如何简化它以使其成为两个子句?

This doesn't work, it says there is a syntax error which I can't quite see, and I know it isn't two clause either. Anyone know how I could simplify it to make it two clause?

推荐答案

和你一样,我使用 'max' 名称作为谓词.此实现不依赖于任何内置谓词:

As you, I use the 'max' name for the predicate. This implementation don't rely in any built-in predicate:

max([X],X).
max([X|Xs],X):- max(Xs,Y), X >=Y.
max([X|Xs],N):- max(Xs,N), N > X.

这篇关于两个子句定义以查找列表上的最大数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆