If condition optimization

56 views
Skip to first unread message

Paulo Matos

unread,
Mar 6, 2018, 8:58:46 AM3/6/18
to Racket-Dev List
Hi,

I tried to disassemble this:

(define (f x y)
(if (and (zero? x)
(= (+ x y) y))
1
0))

In reality this is the same as:
(define (f x y)
(if (zero? x)
1
0))

Except racket does not perform the optimization. What's the reason for
this?

Kind regards,
--
Paulo Matos

Matthew Flatt

unread,
Mar 6, 2018, 9:16:45 AM3/6/18
to Paulo Matos, Racket-Dev List
At Fri, 2 Mar 2018 12:34:00 +0100, "'Paulo Matos' via Racket Developers" wrote:
> (define (f x y)
> (if (and (zero? x)
> (= (+ x y) y))
> 1
> 0))
>
> In reality this is the same as:
> (define (f x y)
> (if (zero? x)
> 1
> 0))

Those turn out to be different. Try `(f 0 +nan.0)` or `(f 0 'symbol)`.

> Except racket does not perform the optimization. What's the reason for
> this?

Even if you throw in enough constraints on the program to make a
similar transformation valid, the optimizer would have to include
specific mechanisms for tracking zero values and number types (more
than it does) and rules on how arithmetic operations interact with
those abstract values. We haven't so far had a reason to create all of
those rules. And as your example illustrates, they'd help less often
than you might expect.

Robby Findler

unread,
Mar 6, 2018, 9:27:58 AM3/6/18
to Matthew Flatt, Paulo Matos, Racket-Dev List
Also: Racket's contract system can help you find inputs that
distinguish these functions. Try this out:

#lang racket
(define (f1 x y)
(if (and (zero? x)
(= (+ x y) y))
1
0))

(define (f2 x y)
(if (zero? x)
1
0))

(define/contract (same? x y)
(-> any/c any/c #t)
(equal? (with-handlers ([exn:fail? exn-message])
(f1 x y))
(with-handlers ([exn:fail? exn-message])
(f2 x y))))

(for ([x (in-range 100)])
(contract-exercise same?))
> --
> You received this message because you are subscribed to the Google Groups "Racket Developers" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to racket-dev+...@googlegroups.com.
> To post to this group, send email to racke...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/racket-dev/5a9ea2cc.1ae0620a.a66d5.9dbdSMTPIN_ADDED_MISSING%40gmr-mx.google.com.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages