[R] unexpected 'else' in " else"

Ebert,Timothy Aaron tebert @end|ng |rom u||@edu
Fri Oct 28 17:22:10 CEST 2022


I appreciate this thread on coding. My preference for reading is to have complete sentences.
I can read this:
{ if (x<y)
    z <- x
  else
    z <- y
}

This is much harder no matter how nicely everything is lined up.
{ if 
    (x<
     y)
       z <- 
       x
  else
       z <- 
       y
}


Regards,
Tim

-----Original Message-----
From: R-help <r-help-bounces using r-project.org> On Behalf Of Jorgen Harmse via R-help
Sent: Friday, October 28, 2022 10:39 AM
To: r-help using r-project.org
Subject: Re: [R] unexpected 'else' in " else"

[External Email]

Richard O'Keefe's remarks on the workings of the interpreter are correct, but the code examples are ugly and hard to read. (On the other hand, anyone who has used the debugger may be de-sensitised to horrible code formatting.) The use of whitespace should if possible reflect the structure of the code, and I would usually rather throw in a few extra delimiters than obscure the structure.

Regards,
Jorgen Harmse.


Examples (best viewed in a real text editor so things line up):


{ if (x<y)
    z <- x
  else
    z <- y
}

Or

{ if(x<y) z <- x
  else z <- y
}

x <- ( y
      + z)

Or

( x
<- y
   + z
)

Or

 


Message: 1
Date: Wed, 26 Oct 2022 23:03:30 +1300
From: "Richard O'Keefe" <raoknz using gmail.com>
To: Jinsong Zhao <jszhao using yeah.net>
Cc: "r-help using r-project.org" <r-help using r-project.org>
Subject: Re: [R] unexpected 'else' in " else"
Message-ID:
        <CABcYAd+=v6FvOqi7JjK7iR5RScVdDBGZK_BASQ-z0=k6TKEyYA using mail.gmail.com>
Content-Type: text/plain; charset="utf-8"

...

The basic issue is that the top level wants to get started on your command AS SOON AS IT HAS A COMPLETE COMMAND, and if (...) stmt is complete.  It's not going to hang around "Waiting for Godot"
for an 'else' that might never ever ever turn up.  So
   if (x < y) z <-
   x else z <- y
is absolutely fine, no braces needed, while
   if (x < y) z <- x
   else z <- y
will see the eager top level rush off to do your bidding at the end of the first line and then be completely baffled by an 'else' where it does not expect one.

It's the same reason that you break AFTER infix operators instead of BEFORE.
   x <- y +
   z
works fine, while
   x <- y
   + z
doesn't.





        [[alternative HTML version deleted]]



More information about the R-help mailing list