Reputation: 89
I'm writing a rule that searches a database of facts in the form:
overground(Station1, Station2, DurationOfTravel).
and allows to you search for all journeys that take the same duration of travel.
I've written these two rules:
timesearch(Duration) :-
overground(Station1, Station2, Duration),
print([Station1, Station2]).
timesearch(Duration, [Station1,Station2]) :-
overground(Station1, Station2, Duration).
Which do essentially the same thing. What I'm unsure about is which is best practice? Or are they two equally good solutions?
Upvotes: 2
Views: 112
Reputation: 7493
In addition to @larsmans's answer, I'd like to add a link about pure functions. In any language where you have the chance to apply this concept, prefer pure functions when possible and handle the IO in separate parts.
Especially here in prolog, when backtracking is needed, the fact that you output things in your business logic predicates might reveal really problematic, since those things may be printed during the execution of a branch that won't lead to a relevant result.
Upvotes: 2
Reputation: 363567
They don't do essentially the same thing; they contain the same "business" logic, but the first mixes in presentation logic (output code). It's a general principle of program design that business logic and presentation should be separated, so go with the second option and put the printing in some kind of main
predicate.
In particular, in this example you don't want the printing to be done in the timesearch
predicate; what if you decide one day that you want a more complicated algorithm that can determine the duration of a route of more than two hops? You can implement such an algorithm in terms of the second definition of timesearch
, but not in terms of the first.
(This has very little to do with Prolog and all the more with the craft of good software design.)
Upvotes: 6