Search code examples
listerlangarea

Calculate Area - Erlang


I have the following function that should calculate an area using each value in the list.

The problem I have is that the function only prints the first result for the first item in the list, and what I need to print for each item in the list.

You can think that each item in the list is a case and I would like to print all cases.

 area([H|_])->(math:sqrt(3.0) * (H*H)) - (3.14 * (H*H))/2;
 area([_|T])-> area(T).     

Solution

  • You've got the recursion wrong. What should be done is that you print the area of the head, then recurse on the tail. You'll also need to add a base case, handling empty list.

    area([]) -> ok;
    area([H|T]) ->
      io:format("~p~n", [(math:sqrt(3.0) * (H*H)) - (3.14 * (H*H))/2]),
      area(T).
    

    If you instead want a list of areas as the result, you can do:

    area([]) -> [];
    area([H|T]) ->
      [(math:sqrt(3.0) * (H*H)) - (3.14 * (H*H))/2 | area(T)].