5
votes

I am running Emacs 24.5.1 on Windows 10 and working through the SICP. The MIT editor Edwin doesn't function well, especially on Windows. Racket appears to be a good alternative. I have installed both Racket and racket-mode and everything seems to run okay. However, racket-mode insists on pretty-printing my results. How do I get it to print in decimal form?

For example,

(require sicp)

(define (square x) (* x x))

(define (average x y)
  (/ (+ x y) 2))

(define (improve guess x)
  (average guess (/ x guess)))

(define (good-enough? guess x)
  (< (abs (- (square guess) x)) 0.001))

(define (sqrt-iter guess x)
  (if (good-enough? guess x)
      guess
      (sqrt-iter (improve guess x)
                 x)))

This produces results such as

> (sqrt-iter 1 2)
577/408

Lots of documentation comes up when I Google the terms "Racket" and "pretty-print," but I'm having no luck making sense of it. The Racket documentation seems to control pretty-printing via some variable beginning with 'pretty-print'. Yet nothing starting with racket- or pretty within M-x comes up. Maybe the fraction form isn't what Racket considers pretty-printing?

3

3 Answers

3
votes

Start the the iteration with floating point numbers 1.0 and 2.0 rather than exact numbers 1 and 2.

The literal 1 is read as an exact integer whereas 1.0 or 1. is read as a floating point number.

Now the function / works on both exact an inexact numbers. If fed exact numbers it produces a fraction (which eventually ends up being printed in the repl).

That is you are not seeing the effect of a pretty printer, but the actual result. The algorithm works efficiently only on floating point numbers as input so you can consider adding a call to exact->inexact to your function.

1
votes

As the other answers explain, it turned out this isn't actually about pretty printing.

However to answer you question literally (if you ever did want to disable pretty printing in racket-mode):

The Emacs variable is racket-pretty-print.

You can view documentation about it using C-h v.

To change it you can either:

  • Use Emacs' M-x customize UI.

  • Use (setq racket-pretty-print nil) in your Emacs init file, for example in a racket-repl-mode-hook.

1
votes

This is actually intentional and is part of the Scheme standard (R5RS, R7RS). It is not restricted to Racket but should be the output of any Scheme interpreter/REPL. It has nothing to do with pretty printing. It is mostly considered a good thing since it is giving you the exact number (rational number) rather than a floating point approximation. If you do want the floating point result then do request it by using 1.0 rather than 1 etc.

> (/ 1.0 3)
0.3333333333333333

Alternatively, you can use the exact->inexact function e.g.

> (exact->inexact 1/3)
0.3333333333333333