Prologue to Erlang

Say you have this prologue term, "city (London, England)." those. London is a city in England.

How do you imagine Erlang matching patterns?

+4
source share
2 answers

There is no simple mapping that can be done between Erlang and Prolog. With the exception of syntax and some operators, they are completely different languages. You cannot do much with Prolog, and there is no good way to do what you ask; they all suck. However, here's what you can do with sucking methods.


Where city(London, England) creates a connection between a city and a country in Prolog, there is no such declarative equivalent in Erlang. To get something somewhat equivalent, you will need to manually store the relationships in memory (lists, ETS table, trees or dictionaries, etc.).

If you use a view a bit like {Rel, [Items]} , you might have your current example as {city, [london, england]} . If you save them to a list, pattern matching can be simple

 relation(X, [X|Rest]) -> true; relation(X, [_|Rest]) -> relation(X, Rest); relation(X, []) -> false. 

or maybe something more like

 main() -> Relations = [{london, england}, {montreal, canada}, {oxford, england}], same_country(Relations, london, oxford). same_country(Relations, City1, City2) -> {_, Country1} = lists:keyfind(City1, 1, Relations), {_, Country2} = lists:keyfind(City2, 1, Relations), COuntry1 == Country2. 

Of course, this is inefficient, and you are likely to use one of the data structures that currently exist in Erlang. In the case of most opaque data structures for storing key values ​​(gb_trees, dict, etc.), you need to use the functions that you need to reproduce, and thus pattern matching is not possible.

The next choice might be to use ETS, an in-memory database for Erlang. It uses another method for matching, called specification matching (or converted from functions that use pattern matching with ets: fun2ms / 1. )

All of the above is not very useful, because it will not allow you to do really effective operations on this ratio. To get maximum functionality, you probably have to use set theory, model the data yourself and work with it using the "Query List" or sofs (Sets Of Sets).


Again, I repeat that there really is no good way to translate any Prolog into Erlang. Earlier versions of Erlang were written in Prolog, but the semantics are simply not the same. If you're interested, you can take a look at Erlog , a prologue to and for Erlang, written by Robert Virgin.

+4
source
 city("London", "England") -> true; city(_, _) -> false. 

OR

 city("London") -> "England"; city(_) -> "". 
+3
source

Source: https://habr.com/ru/post/1314842/


All Articles