Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I define an "or-function" in scheme?

Tags:

scheme

I have found this question about the special function "or" in scheme:

Joe Hacker states loudly that there is no reason or in Scheme needs to be special -- it can just be defined by the programmer, like this:

(define (or x y)
    (if x
        #t
        y))

Is Joe right?

I can't figure out why it shouldn't be possible to do that.

Could some scheme-expert please explain if this works, and if no: why not?

like image 913
Edgar Avatar asked Nov 05 '11 14:11

Edgar


2 Answers

It's because this version of or evaluates all of its arguments (since it's a function), while the standard Scheme or (which is not a function but special syntax) doesn't. Try running (or #t (exit)) at the Scheme REPL and then try the same with your or function.

The behavior of the standard or is sometimes called short-circuited: it evaluates only those arguments that it needs to. This is very common for the binary boolean operator (or and and) across programming languages. The fact that or looks like a function call is a feature of Scheme/Lisp syntax, but looks deceive.

like image 111
Fred Foo Avatar answered Sep 28 '22 01:09

Fred Foo


Whether it works or not depends on what you want it to do. It certainly works in the sense that for two given boolean values it will return the expected resulted. However it will not be functionally equivalent to regular or because it does not short-circuit, i.e. given your definition (or #t (/ 0 0)) will cause an error because you're dividing 0 by 0 while using regular or it would just return #t and not try to evaluate (/ 0 0) at all.

like image 27
sepp2k Avatar answered Sep 28 '22 02:09

sepp2k