HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Sorting numbers in LISP

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sortingnumberslisp

Problem

I am doing a CS practice exercise in which you are supposed to sort exactly three numbers using only if statements. I wrote the following code in LISP and would appreciate any suggestions how to improve on my code. Thank you!

(defun generate-three ()
  (loop for l from 1 to 3 collect (random 25)))

(defun result (a b c) (format t "The sorted result is (~d,~d,~d)~%" a b c))

(let (a b c (the-three (generate-three)))
    (format t "~a ~%" the-three)
    (setq a (first the-three) b (second the-three) c (third the-three))
    (if (< a b)
      (if (< b c) (result a b c)
        (if (< a c) (result a c b) (result c a b)))
      (if (< a c) (result b a c)
        (if (< b c) (result b c a) (result c b a)))))


Based on feedback from commenters, the revised code looks as follows:

(defun my-sort-3 (a b c)
    (if (< a b)
      (if (< b c) (list a b c)
        (if (< a c) (list a c b) (list c a b)))
      (if (< a c) (list b a c)
        (if (< b c) (list b c a) (list c b a)))))

(destructuring-bind (a b c) (loop repeat 3 collect (random 25))
  (format t "The sorted result of (~d,~d,~d) is ~a ~%" a b c (my-sort-3 a b c)))


Latest iteration - note the changes in the final "format" statement:

(defun my-sort-3 (a b c)
    (if (< a b)
      (if (< b c) (list a b c)
        (if (< a c) (list a c b) (list c a b)))
      (if (< a c) (list b a c)
        (if (< b c) (list b c a) (list c b a)))))

(destructuring-bind (a b c) (loop repeat 3 collect (random 25))
  (format t "The sorted result of (~{~d~^, ~}) is (~{~d~^, ~})~%" (list a b c) (my-sort-3 a b c)))

Solution

It's been a while since I've used lisp, so I can't really critique your code for style or any common lisp gotchas.

That said, the biggest thing I notice here is that the code for generating the 3 numbers, sorting them, and printing the result are all tightly coupled with each other. I would suggest defining a separate function that takes three numbers and returns them in sorted order, which can then be combined with your existing functions for generating three numbers and printing three numbers to give the desired output. The added benefit, of course, is that this sort function can later be used to sort any three numbers, not just the three in this bit of code.

Context

StackExchange Code Review Q#1179, answer score: 3

Revisions (0)

No revisions yet.