Pages

Sunday, February 7, 2010

Erlang Ternary Operators

tidier came up with a cool suggestion for some code. One of the case statements:
Valid = case makesum(Hdr) of
    0 -> true;
    _ -> false
end,
was replaced with:
Valid = makesum(Hdr) =:= 0,
Maybe it's succintness at the expense of readability but I liked it.
Sometimes, when I'm programming in Erlang, I miss the C style ternary operators. You know, the ones that look like this:
i = ( (i == 0) ? 1 : 0);
It's an easy way of toggling between values. In Erlang, if you want to flip between true and false, you could write it as:
NewValue = case Value of
    true -> false;
    false -> true
end
But the tidier way reveals a simpler version:
NewValue = Value =/= true
The new version isn't semantically identical to the old version though.
true = foo =/= true
The old version would throw a case_clause exception if value were 'foo'. In both cases, the value of "Value" may already be controlled with guards, so it may be ok.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.