开发者

Can if statements be implemented as function calls?

One of the stylistic 'conventions' I find slightly irritating in published code, is the use of:

if(condition) {

instead of (my preference):

if (condition) {

A slight difference, and probably an unimportant one, but it occurred to me that the first style might be justified if 'if' statements were impl开发者_C百科emented as a kind of function call. Then I could stop objecting to it.

Does anyone know of a programming language where an if statement is implemented as a function call, where the argument is a single boolean expression?

EDIT: I realise the blocks following the if() are problematic, and the way I expressed my question was probably too naive, but I'm encouraged by the answers so far.


tcl is one language which implements if as a regular in built function/command which takes two parameters ; condition and the code block to execute

if {$vbl == 1} { puts "vbl is one" }

http://tmml.sourceforge.net/doc/tcl/if.html

In fact, all language constructs in tcl (for loop , while loop etc.) are implemented as commands/functions.


It's impossible for it to have a single argument since it has to decide which code path to follow, which would have to be done outside of said function. It would need at least two arguments, but three would allow an "else" condition.


Lisp's if has exactly the same syntax as any other macro in the language (it's not quite exactly a function, but the difference is minimal): (if cond then else)

Both the 'then' and 'else' clauses are left unevaluated unless the condition selects them.


In Smalltalk, an if statement is kind of a function call -- sort of, in (of course) a completely object oriented way, so it's really a method not a free function. I'm not sure how it would affect your thinking on syntax though, since the syntax is completely different, looking like:

someBoolean
    ifTrue:  [ do_something ]
    ifFalse: [ do_something_else ]

Given that this doesn't contain any parentheses at all, you can probably interpret it as proving whatever you wanted to believe. :-)


If the if function is to be a regular function, then it can't just take the condition, it needs as its parameters the block of code to run depending on whether the condition evaluates to true or not.

A prototype for a function like that in C++ might be something along the lines of

void custom_if(bool cond, void (*block)());

This function can either call the block function, or not, depending on cond.

In some functional languages things are much easier. In Haskell, a simple function like:

if' True a _ = a
if' _ _ b = b

allows you to write code like this:

if' (1 == 1)
  (putStrLn "Here")
  (putStrLn "There")

which will always print Here.


I don't know of any languages where if(condition) is implemented as a regular function call, but Perl implements try { } catch { } etc.. {} as function calls.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜