Search code examples
prolog

how do i delete char type in list in prolog?


I‘m new to learn prolog, I want to fulfill the predicate below,

this is my code


onlyinteger(List,New):-
    flatten(List,Fla),
    member(X,Fla),
    string(X),
    delete(X,Fla,New).

onlyinteger([[5, 'A'], [5, 'B'],[1,'A'],[3,'C'],[7,'D']],X). -- input

what I want,

X = [5,5,1,3,7].


Solution

  • % Base case, reached at the end of the loop
    only_integer([], []).
    % Add the integer to the output list
    only_integer([[Int, _Char]|Tail], [Int|LstInt]) :-
        % Loop
        only_integer(Tail, LstInt).
    

    Result in swi-prolog:

    ?- time(only_integer([[5, 'A'], [5, 'B'],[1,'A'],[3,'C'],[7,'D']],X)).
    % 6 inferences, 0.000 CPU in 0.000 seconds (82% CPU, 187137 Lips)
    X = [5,5,1,3,7].