3 ms·
In what languages is if a function?
by Bootvis 14y ago
In what languages is if a function?
- entropy_ 14y agoLISP maybe?
- jeremiep 14y agoIn Haskell/Ruby/CoffeeScript: a = if b then c else d In Lisp: (setq a (if b c d)) Only Lisp implements them as a function (more precisely, a macro), but to the programmer there's no difference between using if and calling a function. Of course, they don't compile into function calls in assembly code :)
- tarabukka 14y agoIf is an expression in a lot of languages. The syntax you describe is identical to the "ternary statement" in C-style languages.
- jeremiep 14y agoThe ternary is an expression, not a statement :) You can write: a = b ? c : d; in C/C++, you can't write a = if(b) { c; } else { d; }.
- tarabukka 14y agoOh, yeah. My mistake. Although what you describe is a lot more functional in style. You could probably emulate it in a language with higher-order functions.
- adobriyan 14y agoIt is called "special form". http://www.lispworks.com/documentation/HyperSpec/Body/03_ababa.htm http://www.lispworks.com/documentation/HyperSpec/Body/03_aba... IF can't be implemented as a function because of evaluation rules.
- jeremiep 14y agoAh, that is correct. You can't use if as a first-class function in Lisp. I still thought you could pass macros around like normal functions in Common-Lisp. The Lisp interpreter I wrote for fun could do that since the function value is resolved before arguments are evaluated for late macro expansions.
- Bootvis 14y agoAlso R and I think were mostly in agreement here. However I'm of the opinion that more than just these languages (languages with lazy evaluation or macro's) are decent and that in for example Ruby there are differences between if and a function, as this example shows (my first lines of Ruby) def iff(cond, x, y) if cond then x else y end end puts iff(true, 1, puts('2')) echoes 2 1 if may behave as a function, but you can't write a function that acts like if. edit: R does have real lazy evalution, e.g. > iff <- function(cond, x, y) { if (cond) x else y } > iff(TRUE, 1, cat('foo')) [1] 1
- philwelch 14y agoThere is a difference to the programmer, and it's pretty important as far as "if" goes: if "if" were a function, its arguments would need to be evaluated before they were passed in, which defeats the purpose of "if", which is to conditionally execute only one branch.
- tomjakubowski 14y agoYou did say that only Lisp implements "if" as a function, but I thought I'd share that in Haskell "if" is syntactic sugar for a case expression. That is: if x then y else z is sugar for: case x of True -> y False -> z There have been suggestions to replace this sugaring with a proper "if" function, e.g.: if :: Bool -> a -> a -> a if True x _ = x if False _ y = y to remove arguably redundant syntax, but it seems unlikely that this change would happen. See more here: http://www.haskell.org/haskellwiki/If-then-else http://www.haskell.org/haskellwiki/If-then-else