[erlang-questions] Inline If

Robert Virding rvirding@REDACTED
Sun May 9 14:55:07 CEST 2010


On 9 May 2010 12:21, Zoltan Lajos Kis <kiszl@REDACTED> wrote:
> On 5/9/2010 11:05 AM, Masklinn wrote:
>>
>> On 2010-05-09, at 01:20 , Zoltan Lajos Kis wrote:
>>
>>>
>>> I guess the ternary operator only makes sense in non-functional
>>> languages, where conditional statements do not have return values.
>>> Given that there was no ternary operator, you would have to duplicate the
>>> assignment part, rendering the code less readable:
>>>
>>> if (a) { x = b; } else { x = c; };
>>> /* x = a ? b : c; */
>>>
>>> In a functional language, such as Erlang, the these statements do have a
>>> return value, so the ternary-operator would only be a syntactic sugar:
>>>
>>> X = case A of true ->  B; false ->  C end.
>>>
>>
>> For that precise case, using if would probably be a bit shorter (thought
>> the second case might not be as readable):
>>
>> X = if A ->  B; true ->  C end.
>>
>>
>>
>
> I don't favor the "if" statement exactly because of  the "true case". If I
> had to use if, I would do it this way:
>
> X = if A -> B; (not A) -> C end.

You are thinking conventional 'if', view it rather as a (cond ...)
with restricted tests or as a short form of

case 1 of
    _ when ... -> ...;
    _ when ... -> ...;
    ...
end

(which it really is) and it all becomes clearer and more logical. :-)

Robert


More information about the erlang-questions mailing list