Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

filter - how should I delete non numbers in list use prolog

I should remove all elements of List that are not a number greater than number. I can solve it just for numbers. but when the list has some symbolic how should I delete.this is my code

greater_nrs_only( X, List, Ans) :-
    greater_nrs_only( X, List, Ans, [] ), !.

greater_nrs_only( _, [], Ans, Ans).
greater_nrs_only( X, [H | Tail], Ans, Acc ) :-
    (
        ( H < X, NewEl = [] )
        ;
        ( H >= X, NewEl = [H] )
    ),
    append( Acc, NewEl, NewAcc ),
    greater_nrs_only( X, Tail, Ans, NewAcc).

and ?- greater_nrs_only(6, [ ], X). is false


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The reason this will error is because H is not per se a number, so comparing 6 with a for example will raise an error. You can use number/1 [swi-doc] to check if something is a number.

Instead of doing filtering manually, you can also work with include/3 [swi-doc], which filters the list for items that satisfy a given predicate:

greater_than(X, Y) :-
    number(Y),
    X < Y.

greater_nrs_only(X, L, R) :-
    include(greater_than(X), L, R).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...