Prolog return 日期和与之关联的事件

Prolog return date and event associated with it

大家好,我已经研究这个问题几个小时了,但我可以解决它,如果你们能给我提示,那就太好了! 问题很长,但据我所知,解决方案不会超过 5 行。

所以我得到了一堆数据,可以说:

day(1,1, 'New Year')
day(2,1, 'The day after the new year')
day(23,1, 'The day i will finally understand this language :)')
day(14,2, 'Valentin's day')
day(16,2, 'Family day')
day(22,2, 'hein.. dont now lol')

所以第一个数字是日期、第二个月和第三个事件,并且 其他月份以此类推。每个月也有一个天数:

nday(1,31).
nday(2,28).
nday(3,31).
nday(4,30).
nday(5,31).

如果我输入 DayofTheMonth(1,L),这样 L 是一个列表,1 月 1 日, 我应该 return 列出那个月的所有日子以及发生的事件。 在这种情况下,它应该是:[(1,'New year', (2,'The day after the new year'), (23, 'The day i will finally understand this language :)')]。这就是我所做的:(我什至不知道基本情况 smh)我很抱歉我知道 这个解决方案是错误的,它甚至不处理没有事件的日子, 但我只是不知道该去哪里,我只是提供反馈或其他东西

dayoftheMonth(X, L):- nday(X,Answer), 
                  dayMonth(X, Answer, L).
dayMonth(X,Y,[_|B]):- 
    X=<Y,
    day(Day, X, Event),
    W is Day + 1,
    dayMonth(X,W,[(Day,Event)|B]). 

您可以为此使用谓词 findall/3。谓词有三个参数:

  • template,输出的格式
  • goal,你调用的谓词应该匹配
  • bag,谓词的返回列表。

所以 dayofTheMonth 简单地读作:

dayofTheMonth(Month,List) :-
    findall((Day,Event),day(Month,Day,Event),List).

如果你想在没有findall的情况下解决它,你可以通过遍历所有天数直到天数来解决它。因此 basecase 是当 day 已经超过了一个月的天数。

dayofTheMonth(Month,Day,[]) :-
    nday(Month,Threshold),
    Day > Threshold,
    !.

归纳案例总是看当天是否有计划的事件,如果有,你把它作为列表的头部,并在第二天追加事件,如果没有这样的事件,结果list 是接下来几天的列表。所以:

dayofTheMonth(Month,Day,[(Day,Event)|T]) :-
    day(Day,Month,Event),
    !,
    Day1 is Day+1,
    dayofTheMonth(Month,Day1,T).
dayofTheMonth(Month,Day,T) :-
    Day1 is Day+1,
    dayofTheMonth(Month,Day1,T).

最后,你只需要 link 谓词 dayOfTheMonth/2dayOfTheMonth/3 开始 - 显然 - 按天 1.

dayofTheMonth(Month,Events) :-
    dayofTheMonth(Month,1,Events).

所以完整代码如下:

day(1,1, 'New Year').
day(2,1, 'The day after the new year').
day(23,1, 'The day i will finally understand this language :)').
day(14,2, 'Valentins day').
day(16,2, 'Family day').
day(22,2, 'hein.. dont now lol').

nday(1,31).
nday(2,28).
nday(3,31).
nday(4,30).
nday(5,31).

dayofTheMonth(Month,Day,[]) :-
    nday(Month,Threshold),
    Day > Threshold,
    !.

dayofTheMonth(Month,Day,[(Day,Event)|T]) :-
    day(Day,Month,Event),
    !,
    Day1 is Day+1,
    dayofTheMonth(Month,Day1,T).
dayofTheMonth(Month,Day,T) :-
    Day1 is Day+1,
    dayofTheMonth(Month,Day1,T).
dayofTheMonth(Month,Events) :-
    dayofTheMonth(Month,1,Events).