简体   繁体   中英

Reading and storing all words of file in prolog

I am a newbie to prolog, till now I am able to read all words of file, displayed them one by one, now I want to store them in a list(one by one, as I soon as I am displaying them). All logic for append given everywhere, append content of two lists in an empty list. For example append(new_word,word_list,word_List), intially my word_list is empty, so everything fine, but afterwards it says no, and stop at that point. Need help to be able to store element in list one by one.

You can use difference lists :

file_to_list(W, L) :-
   read_word(Word),
   append_dl(W, [Word|U]-U, Ws),
   !, file_to_list(Ws, L).

file_to_list_1(Ws, Ws).


append_dl(X-Y, Y-Z, X-Z).

You call file_to_list(UU, L-[]) to get the list of words. There is no slowdown but takes more inferences than CapelliC's code (one per word).

Let say you have a predicate read_word(W) that fetch W and fails when there are no more. Then with this definition

file_to_list_rev([W|Ws]) :-
   read_word(W),
   !, file_to_list_rev(Ws).
file_to_list_rev([]).

a query file_to_list_rev(R),reverse(R, L) , will store all words (in reverse order) in R, and in L the ordered list.

edit I must still be sleeping... That code dosn't build a reverse list... please consider

file_to_list([W|Ws]) :-
   read_word(W),
   !, file_to_list(Ws).
file_to_list([]).

and drop altogether the reverse/2 at end.

edit done

Note that appending each word to the end of the list would result in big slowdown, turning a 'linear size' problem into a 'quadratic' one. Anyway, this could be accomplished in this ugly way (note we need a service variable):

file_to_list(L) :-
    file_to_list([], L).

file_to_list(SoFar, L) :-
   read_word(W),
   append(SoFar, [W], Temp),
   !, file_to_list(Temp, L).
file_to_list(L, L).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM