Saturday, January 07, 2006

Celsius to Fahrenheit in Scheme

Converting from C to F is trival - just multiple the temperature in C with 9/5 and then add 32.
So, a scheme version of this would look something like this
(define (celsius-fahrentheit c)
(+ (* c (/ 9 5)) 32))

However, this gives results out as fractions. So, (celsius-fahrenheit 32) gives the result as
448/5

Therefore, the correct implementation would be
(define (celsius-fahrentheit c)
(+ (* c (/ 9.0 5.0)) 32.0))

This gives the result as
89.6.
We can also define a new function that prints a table of celsius and fahrenheit values.
Ideally, this function would be using recursion instead a loop to go through all the
functions.
(define (celsius-fahrenheit-table min-value max-value)
(let ((c min-value))
(if (<= c max-value) (begin (display c) (display "<->")
(display (celsius-fahrenheit c))
(newline))
(celsius-fahrenheit-table (+ min-value 1) max-value))
0)))

However, the display bit can also be moved out to a separate function
(define (display-items x y)
(display y)
(display "<->")
(display (x y))
(newline))

Then, our function will look like this
(define (celsius-fahrenheit-table min-value max-value)
(let ((c min-value))
(if (<= c max-value)
(begin
(display-items celsius-fahrenheit c)
(celsius-fahrenheit-table (+ min-value 1) max-value)) 0)))

But the biggest change for a C program is the fact that functions are first class objects. What this means, is that we can use functions in interesting ways. We can define separate functions for celsius to fahrenheit conversion and vice versa, and pass them around. That means, we have a generic function that prints a table.

(define (tabulate convertor min-value max-value)
(define (display-items x y)
(display y) (display "<->")
(display (x y))
(newline))

(let ((x min-value))
(if (<= x max-value)
(begin
(display-items convertor x)
(tabulate convertor (+ x 1) max-value))
0)))

(define (celsius-fahrenheit-table min-value max-value)
(tabulate celsius-fahrenheit min-value max-value))

(define (fahrenheit-celsius-table min-value max-value)
(tabulate fahrenheit-celsius min-value max-value))

If you are interested in learning more about scheme then schemers.org is a great starting point. I also have a page maintaining some of my posts on scheme. 

No comments: