开发者

Prolog term to Erlang

Let's say you have this prolog开发者_开发百科 term "city(London, England)". ie London is a city in England.

How do you represent that in Erlang, pattern matching?


There is no simple mapping that can be done between Erlang and Prolog. Except for the syntax and some operators, they're completely distinct languages. You won't be able to do much from Prolog and there is no good way to do what you ask; they all suck. Nevertheless, here's what could be possible to do with the sucky methods.


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

If you use a representation a bit like {Rel, [Items]}, you could have your current example as {city, [london, england]}. If you store them all in a list, pattern matching could simply be

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're likely to use one of the data structures that currently exist in Erlang. In the case of most opaque data structures for key-value storage (gb_trees, dict, etc.), you need to use the functions given to you to play around and thus no pattern matching is possible.

The next choice could be to use ETS, an in-memory database for Erlang. It uses a different method for matching, named match specs (or converted from functions that use pattern matching with ets:fun2ms/1.)

All of the above isn't really useful because it won't let you do any really efficient operations on the relationship. To get the most functionality you'd probably have to use set theory, model the data yourself and operate on it with the help of Query List Comprehensions or the sofs (Sets Of Sets) module.


Again, I'll repeat there's really no good way to translate any Prolog to Erlang. Early versions of Erlang were written in Prolog, but the semantics just aren't the same. If you're interested, you could take a look at Erlog, a Prolog in and for Erlang written by Robert Virding.


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

OR

city("London") -> "England";
city(_) -> "".
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜