Search code examples
recursionprolog

Prolog: delete all spaces in list


I have list of lists like this:

[[q, ,w, ,e, ,r, ,t, ,z],[a, ,s, ,d, ,f, ,g, ,h],[y, ,x, ,c, ,v, ,b, ,n]]

and I need to delete all spaces except in last list. So I want:

[[q,w,e,r,t,z],[a,s,d,f,g,h],[y, ,x, ,c, ,v, ,b, ,n]]

I tried:

deleteAll([_|[]],[]).
deleteAll([Head|Tail],L) :-
  deleteAll(Tail,_),
  subtract(Head,[ ],L).

But it doesnt work. I'm getting onlny:

[q, ,w, ,e, ,r, ,t, ,z]

So it seems that even subtract didnt match the [ ] as space. How can I achieve this?


Solution

  • :- set_prolog_flag(double_quotes, chars).
    :- use_module(library(double_quotes)).
    
    spdels([], []).
    spdels([Cs], [Cs]).
    spdels([Cs|Css], [Ds|Dss]) :-
       Css = [_|_],
       Dss = [_|_],
       text_nospaces(Cs, Ds),
       spdels(Css, Dss).
    
    text_nospaces([], []).
    text_nospaces([C|Cs], Ds0) :-
       if_(C = ' ', Ds0 = Ds1, Ds0 = [C|Ds1] ),
       text_nospaces(Cs, Ds1).
    
    
    text_nospaces_bis(Cs, Ds) :-
       tfilter(dif(' '), Cs, Ds).
    

    using if_/3 and tfilter/3.

    ?- spdels(["a b c","d e","f g"], Cs).
       Cs = ["abc","de","f g"]
    ;  false.