[erlang-questions] Trying to learn the Erlang Way

Gustav Simonsson <>
Fri Feb 7 22:32:41 CET 2014

Time for Higher Order Functions Friday Evening (HOFFE)!

I renamed and refactored the cull functions a bit to give a example of
using higher order functions instead of manual recursion.

To answer your other question about objects, one minimal example below is
the spaceship object defined as a two tuple consisting of {Stuff, Vector}.
In the example below I just put a atom in the stuff element, but it could
as well be a complex term. It is ignored by the filtering function.


%% Subtract the second vector from the first
subtract({X1, Y1, Z1}, {X2, Y2, Z2}) -> {(X1 - X2), (Y1 - Y2), (Z1 - Z2)}.

%% Compute the magnitude of the vector
magnitude({X, Y, Z}) -> math:sqrt((X * X) + (Y * Y) + (Z * Z)).

%% Compute whether the vector with components X, Y and Z has greater
magnitude then the passed scalar M.
%% Note that this method avoids the expensive sqrt operation.
is_magnitude_greater(M, {X, Y, Z}) ->
    Msq = M * M,
    Magsq = (X * X) + (Y * Y) + (Z * Z),
    Msq > Magsq.

%% Determines if any coordinate in the given vector is bigger than the
passed in value M
has_coordinate_greater_than(V, {X, Y, Z}) -> X > V orelse Y > V orelse Z >
has_coordinate_greater_than(_, _) -> false.

%% Vector is in the sphere devined by vector C as a center and R as a
in_sphere(C, R, Vector) ->
    case has_coordinate_greater_than(R, Vector) of
        true -> false;
        false -> is_magnitude_greater(R, subtract(C, Vector))

cull(C, R, Vectors) ->
    lists:filter(fun(Vector) -> in_sphere(C, R, Vector) end, Vectors).

cull_spaceships(C, R, Spaceships) ->
    InSphere = fun({_SpaceshipStuff, SpaceshipVector}) ->
                       in_sphere(C, R, SpaceshipVector) end,
    lists:filter(InSphere, Spaceships).


34> v:cull_spaceships({3,3,3}, 5, [{spaceship_stuff, {4,4,4}}]).

On Fri, Feb 7, 2014 at 10:25 PM, Jesper Louis Andersen <
> wrote:

> On Fri, Feb 7, 2014 at 5:45 PM, kraythe . <> wrote:
>> Now the question is the resolution of the followup question of how to
>> integrate this in a solution. Do we return a list of trues and falses and
>> zip that with the objects to form a candidate list? How would you do it?
> Look at lists:partition/2 then write your culler so it can be given as a
> predicate to partition.
> --
> J.
> _______________________________________________
> erlang-questions mailing list
> http://erlang.org/mailman/listinfo/erlang-questions
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20140207/cd2092c4/attachment.html>

More information about the erlang-questions mailing list