Reputation: 68
I got home yesterday and decided to try and write a scheme program that would sort three numbers in ascending order. This is what I came up with:
(define a 3)
(define b 2)
(define c 1)
(define temp 0)
(cond
( (> a c) (set! temp c) (set! c a) (set! a temp))
( (> b c) (set! temp c) (set! c b) (set! b temp))
( (> a b) (set! temp b) (set! b a) (set! a temp))
( (> b c) (set! temp c) (set! b c) (set! b temp))
)
(display a)
(display b)
(display c)
Is that a functional way of solving the problem? What would you suggest?
Upvotes: 1
Views: 1681
Reputation: 492
Scheme has a builtin sort function that is actually faster in some cases than all the sort alorithms we use.
(sort < '(5 2 6))
returns
'(2 5 6)
The main problem that I see with your procedure is that you're only running a swap once. That's great if you can guarantee that one will always be in the middle of the other two, but I'm not so sure that it will always be the case. Also set! is kinda ugly and when I learned scheme my professor told me not to use it because it was resource intensive and there are better ways to do it. I would recommend putting them all in a list and then sorting them and pulling them out of the list if you want to do it that way.
Upvotes: 2