
% temperature conversions using prolog structures

temperature(kelvin, T) :- number(T), T >= 0.
temperature(celsius, T) :- number(T), T >= -273.15.
temperature(fahrenheit, T) :- number(T), T >= -459.67.

% if both scales are the same then both temperatures should be too
convert(temperature(Scale, T), temperature(Scale, T)).

% if we're given the kelvin, we can figure out the celsius
convert(temperature(kelvin, T1), temperature(celsius, T2)) :-
   temperature(kelvin, T1), Temp is T1 - 273.15, T2 = Temp.
   
% if we're given the kelvin, we can figure out the farenheight
convert(temperature(kelvin, T1), temperature(fahrenheit, T2)) :-
   temperature(kelvin, T1), Temp is T1 * 1.8 - 459.67, T2 = Temp.
   
% if we're given the celsius, we can figure out the farenheight
convert(temperature(celsius, T1), temperature(fahrenheit, T2)) :-
   temperature(celsius, T1), Temp is T1 * 1.8 + 32, T2 = Temp.
   
% if we're given the celsius, we can figure out the kelvin
convert(temperature(celsius, T1), temperature(kelvin, T2)) :-
   temperature(celsius, T1), Temp is T1 + 273.15, T2 = Temp.

% if we're given the fahrenheit, we can figure out the kelvin
convert(temperature(fahrenheit, T1), temperature(kelvin, T2)) :-
   temperature(fahrenheit, T1), Temp is (T1 + 459.67)/1.8, T2 = Temp.

% if we're given the fahrenheit, we can figure out the celsius
convert(temperature(fahrenheit, T1), temperature(celsius, T2)) :-
   temperature(fahrenheit, T1), Temp is (T1 -32)/1.8, T2 = Temp.
   
% if we're given the second one but NOT the first,
%    then solve it with a call to the reverse
convert(temperature(Scale1, T1), temperature(Scale2, T2)) :-
   temperature(Scale2, T2), var(T1), 
   convert(temperature(Scale2, T2), temperature(Scale1, T1)).


