Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Basic example of creating a record and iterating over a list of elements.
-module(poc).
-export([all/0,say_hello/1]).
-record(person,{name,genre,age}).
new_person(Name, Genre, Age) ->
#person{name=Name, genre=Genre, age=Age}.
isOlderThanAveragePeople(Age,AverageAge)->
Age>=AverageAge.
say_hello(Person)->
case Person#person.genre of
"m" ->
io:fwrite("Hello mister ~p , you're ~w and you are older than average people\n", [Person#person.name, Person#person.age]);
"f" ->
io:fwrite("Hello miss ~p , you're ~w and you are older than average people\n", [Person#person.name, Person#person.age])
end.
all() ->
John = new_person("John","m",33),
David = new_person("David","m",18),
Mick = new_person("Mick","m",42),
Mariah = new_person("Mariah","f",51),
Sarah = new_person("Sarah","f",11),
People = [John,Mariah,David,Mick,Sarah],
AverageAge = round(calculate_total_age(People) / length(People)),
io:fwrite("The average age is ~w years old.\n",[AverageAge]),
iterate(People,AverageAge).
iterate([Person],AverageAge) ->
case isOlderThanAveragePeople(Person#person.age,AverageAge) of
true -> say_hello(Person);
_ ->ok
end;
iterate([Person|People],AverageAge) ->
case isOlderThanAveragePeople(Person#person.age,AverageAge) of
true -> say_hello(Person);
_ ->ok
end,
iterate(People,AverageAge);
iterate([],_) ->
ok.
calculate_total_age([Person]) ->
Person#person.age;
calculate_total_age([Person|People]) ->
Person#person.age+calculate_total_age(People);
calculate_total_age([]) ->
0.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment