我已经有以下代码:
"atom_length(Var, Len) :- length(Var, Len)."
我想构造一个谓词atom_lengths / 2,它与原子列表做同样的事情:
?- atom_lengths([one, two, three, four], [3, 3, 5, 4]).
true.
?- atom_lengths([one, two, three, four], LS).
LS = [3, 3, 5, 4].
?- atom_lengths([], LS).
LS = [].
如何写“atom_lengths”?? 提前谢谢!
答案 0 :(得分:2)
使用maplist
+ atom_length
:
?- maplist(atom_length, [one, two, three, four], [3, 3, 5, 4]).
true.
?- maplist(atom_length, [one, two, three, four], Ls).
Ls = [3, 3, 5, 4].
?- maplist(atom_length, [], Ls).
Ls = [].
答案 1 :(得分:1)
您不能使用length/2
来计算原子的长度。
但是,您可以先将每个原子转换为atom_chars/2
的字符列表,然后使用length/2
来获取其长度:
atom_lengths([], []).
atom_lengths([Atom|Atoms], [Length|LAtoms]):-
atom_chars(Atom, L),
length(L, Length),
atom_lengths(Atoms, LAtoms).
测试:
?- atom_lengths([one, two, three, four], LS).
LS = [3,3,5,4]
您也可以使用ISO内置谓词atom_chars/2-length/2
,而不是使用atom_length/2
对:
atom_lengths([], []).
atom_lengths([Atom|Atoms], [Length|LAtoms]):-
atom_length(Atom, Length),
atom_lengths(Atoms, LAtoms).
或使用findall/3
:
atom_lengths(Atoms, LAtoms):-
findall(Length, (member(Atom, Atoms), atom_length(Atom, Length)), LAtoms).
根据评论者的建议,更好的习语是使用maplist/3
:
atom_lengths(Atoms, LAtoms):-
maplist(atom_length, Atoms LAtoms).