0

私はPrologを学んでおり、文字列のリストを変換する方法が必要です:

['f(a,45)', 'f(b,13)', 'f(c,12)']

次のようなペアのリストに変換します。

[[45,'a'],[13,'b'],[12,'c']]
4

2 に答える 2

1

これは文字列ではなく、アトムのリストです。Prolog の文字列は通常、次のように表現される文字コードのリストです。

["f(a,45)", "f(b,13)", "f(c,12)"]

とにかく、再帰関数を使用して各要素に変換を適用します。

convert([], []).
convert([Atom|Atoms], [Pair|Pairs]) :-
  convert_element(Atom, Pair),
  convert(Atoms, Pairs).

再帰の代わりに、次のようにmaplist /3 を使用できます。

convert(As, Ps) :- maplist(convert_element, As, Ps).

要素を変換するには、パーサーが必要です。DCG は便利です。

convert_element(Atom, [N, A]) :-
  atom_codes(Atom, Codes),
  phrase(("f(", atomc(Ac), ",", numc(Nc), ")"), Codes, []),
  atom_codes(A, Ac),
  number_codes(N, Nc).

atomc(A) --> ([C], {is_lowerc(C)}, atomc(Cs), {A = [C|Cs]}) ; {A = []}.
numc(N) --> ([C], {is_numc(C)}, numc(Cs), {N = [C|Cs]}) ; {N = []}.

is_lowerc(C) :- C @>= 0'a, C @=< 0'z.
is_numc(C) :- C @>= 0'0, C @=< 0'9.

テスト:

?- convert(['f(a,45)', 'f(b,13)', 'f(c,12)'],L).
L = [[45, a], [13, b], [12, c]] .

atomc//1 と numc//1 はコンパクトな方法で表現されていますが、非常に単純な再帰パターン マッチング手順です。つまり、atomc//1 は次のようになります。

atomc([C|Cs]) --> [C], {is_lowerc(C)}, !, atomc(Cs).
atomc([]) --> [].
于 2012-05-26T19:39:35.693 に答える
0

または、次のコードを使用できます。

convert :-
    L = ["f(a,45)", "f(b,13)", "f(c,12)"],
    maplist(extract_args,L, LA),
    writeln(LA).


extract_args(S, [A1,A2]) :-
    string_to_atom(S, A),
    term_to_atom(T, A),
    T =..[_, A2, A1].

アトムがある場合は、extract_args/2でterm_to_atom/2を使用してください。

于 2012-05-26T20:48:12.670 に答える