开发者

Prolog: nested list

I have this Prolog code:

pick_number_simple([],[开发者_如何学JAVA]).
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).

which gets the numbers out a list. For example:

pick_number_simple([d,f,7,5,e,3,g], NumList)

gives you:

[7,5,3]

But I want to make it get the numbers off of a nested list.

For example:

pick_numbers_general([a,b,1,[2,[c,3]],d],1,NumList)

Would give you:

[2,3]

how do I do this?


U may use 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).

So

?- pick_numbers_general([a,b,1,[2,[c,3]],d],1,NumList).
NumList = [2, 3] ;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜