我有这个Prolog代码:
pick_number_simple([],[]).
pick_number_simple([H|T],[H|T2]):-
number(H), pick_number_simple(T,T2).
pick_number_simple([H|T],T2):-
not(number(H)), pick_number_simple(T,T2).
从列表中获取数字。例如:
pick_number_simple([d,f,7,5,e,3,g], NumList)
给你:
[7,5,3]
但我想让它从嵌套列表中获取数字。
例如:
pick_numbers_general([a,b,1,[2,[c,3]],d],1,NumList)
会给你:
[2,3]
我该怎么做?
答案 0 :(得分:1)
你可以使用flatten/2 predicate
pick_number_simple([],[]).
pick_number_simple([H|T],[H|T2]):-
number(H), pick_number_simple(T,T2).
pick_number_simple([H|T],T2):-
not(number(H)), pick_number_simple(T,T2).
pick_numbers_general(List, Num, NumList) :-
flatten(List, NestList),
pick_number_simple(NestList, NumListAll),
findall(X, (member(X, NumListAll),X > Num), NumList).
所以
?- pick_numbers_general([a,b,1,[2,[c,3]],d],1,NumList).
NumList = [2, 3] ;