问题
I am trying to convert total minutes(N) to number of hours(H) and number of minutes(M) in prolog using this code (Have not implemented counting the minutes yet):
minutes_to_hours(N, H, M) :-
( N >= 60
-> H is H1+1,
N is N1-60,
minutes_to_hours(N, H, M)
; writeln(H)
).
I get this error:
Arguments are not sufficiently instantiated
In:
[2] _1440 is _1446+1
[1] mins_to_hours_and_mins(60,_1508,_1510) at line 1
回答1:
As you requested, a possible solution using recursion could be:
minutes_to_hours(Mins,Hours) :-
( Mins > 60 ->
M is Mins - 60,
H1 is Hours + 1,
minutes_to_hours(M,H1) ;
format('Hours: ~w, Reminder: ~w~n',[Hours,Mins])
).
?- minutes_to_hours(125,0).
Hours: 2, Reminder: 5
true
However, you should prefer the solution of @CapelliC with mod
and //
.
回答2:
H1 is not instantiated, hence the error. But note there is no need for recursion, you can do it similarly to other languages:
?- [user].
|: minutes_to_hours(N, H, M) :-
|: H is N // 60,
|: M is N mod 60.
|: ^D% user://1 compiled 0.05 sec, 1 clauses
true.
?- minutes_to_hours(125,H,M).
H = 2,
M = 5.
来源:https://stackoverflow.com/questions/60262036/converting-minutes-to-hours-in-prolog