Erlang (programming language)/Tutorials/List Comprehensions: Difference between revisions
imported>Eric Evers |
imported>Eric Evers |
||
Line 1: | Line 1: | ||
===Intermediate list comprehensions=== | ===Intermediate list comprehensions=== | ||
Line 100: | Line 42: | ||
17> think:father_of() ++ think:mother_of(). | 17> think:father_of() ++ think:mother_of(). | ||
[{adam,cain},{adam,abel},{noah,shem},{eve,cain},{eve,abel}] | [{adam,cain},{adam,abel},{noah,shem},{eve,cain},{eve,abel}] | ||
Revision as of 15:10, 15 April 2009
Intermediate list comprehensions
An important use of List Comprehensions is to help translate prolog into erlang.
1- Erlang is a functional language designed for message passing (MIMD) parallel processing. Prolog is designed for logic programming. Sometimes a problem is most easily defined as a logical set of constraints on some set of data. If one thinks logically or thinks in constraints, or thinks in prolog, this style of list comprehensions can be a helpful way to do your tasks in erlang. There exist many useful solutions in prolog that can be moved to erlang via list comprehensions.
2- Constraint programming and logic programming are considered a higher level way to program then functions, and hence, are a good way to save you time and increase terseness.
Warning: constraint and logic based programs can be harder to debug because strict step by step actions are hidden and delegated to the list comprehension engine. Order of constraints in erlang list comprehensions can affect the output. Order dependence of constraints can be a non-intuitive distraction.
Note: in general using huge numbers of atoms is not a good idea.
-module(think). % -compile(export_all). % % male(adam) -> true; % male(seth) -> true; male(cain) -> true; male(abel) -> true; male(noah) -> true; male(_X) -> false. % female(eve) -> true; female(_X) -> false. % parent(adam,cain) -> true; parent(adam,abel) -> true; parent(eve,cain) -> true; parent(eve,abel) -> true; parent(noah,shem) -> true; parent(_X,_Y) -> false. % people() -> [ adam, shem, cain, abel, eve, noah ]. % father_of() -> [ {X,Y} || X <- people(), Y <- people(), parent(X,Y), male(X) ]. mother_of() -> [ {X,Y} || X <- people(), Y <- people(), parent(X,Y), female(X) ].
compile with c(think). and generate output with:
17> think:father_of() ++ think:mother_of(). [{adam,cain},{adam,abel},{noah,shem},{eve,cain},{eve,abel}]