[erlang-questions] A matter of style?
Ladislav Lenart
lenartlad@REDACTED
Fri Aug 13 17:33:18 CEST 2010
Iñaki Garay wrote:
> Hello everyone,
> while coding a spatial indexing tree, I often use a small helper
> function within/9, which given three sets of xyz coordinates
> describing three points, returns true when first point lies within the
> bounding box created by the other two points.
>
> This is nothing more than:
>
> within(X, Y, Z, Xmin, Ymin, Zmin, Xmax, Ymax, Zmax) ->
> (Xmin =< X) and
> (X =< Xmax) and
> (Ymin =< Y) and
> (Y =< Ymax) and
> (Zmin =< Z) and
> (Z =< Zmax).
>
> I ask of you this, what difference, if any, is there between using an
> if clause and this function, and inserting the body of this function
> as a guard?
> There is the obvious code reuse when using the function, instead of
> copy-pasting the body. But it makes me do this:
>
> Within = within(X, Y, Z, Xmin, Ymin, Zmin, Xmax, Ymax, Zmax),
> if
> Within ->
> do_something()
> true ->
> {error,out_of_bounds}
> end.
>
> which I dislike for personal reasons.
> Is using a guard more efficient than calling a function? Is the impact
> negligible even when done many times? Or is it a matter of style?
> Do you see a better way?
Hello,
I would use "case" instead of "if" precisely because case allows
full expressions and not only guards:
case within(...) of
true -> do_something();
false -> {error, ouf_of_bounds}
end.
HTH,
Ladislav Lenart
More information about the erlang-questions
mailing list