Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

erlang
communitycreator

List comprehension in Erlang

harris910

Overview

In Erlang, list comprehensions are used to make new lists out of old ones.

[ExpressionQualifier1,Qualifier2,Qualifier3,...][Expression \|\| Qualifier1, Qualifier2, Qualifier3, ...]

Syntax

  • Any expression can be used on the left side of ||.
  • The right side of || is the qualifier, either a generator or a filter.
  • Generator: It extracts each element from the List, one by one. It is written as a Pattern.
  • Filter: It filters the elements of the list. It can be a boolean expression.

Example

[X || X <- [1,7,z,9,4,b,2,6], X > 5].

This should be read like this:

  • The list of X such that X is taken from the list i.e. [1,7,z,9,4,b,2,6] and X is greater than 5.

Expression: X

Generator: X <- [1,7,z,9,4,b,2,6]

Filter: X > 5

-module(main).
-export([main/0]).
main() ->
    OldList = [1,7,z,9,4,b,2,6],
    io:fwrite("OldList:~w~n",[OldList]),

    %List comprehension 
    io:format("Get the elements greater than 5 from OldList~n", []),
    GreaterThan5=[X || X <- [1,7,z,9,4,b,2,6], X > 5],
    io:fwrite("GreaterThan5:~w~n",[GreaterThan5]),

    io:format("Get the odd elements from OldList~n", []),
    Odds = [X || X <- OldList, X rem 2 =/= 0],
    io:format("Odds:~p~n", [Odds]),

    io:format("Get the elements that are odd and greater than 5 from OldList~n", []),
    NewList_Odd_GreaterThan5 = [X || X <- OldList, X rem 2 =/= 0, X > 5],
    io:format("NewList_Odd_GreaterThan5:~p~n", [NewList_Odd_GreaterThan5]).


List comprehension

Explanation:

  • Lines 8 to 10: We print the elements greater than five from OldList using list comprehension.

  • Lines 12 to 14: We print the odd elements from OldList using list comprehension.

  • Lines 16 to 18: We print the elements that are odd and greater than 5 from OldList using list comprehension.

RELATED TAGS

erlang
communitycreator
RELATED COURSES

View all Courses

Keep Exploring