Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

list of ascii to list of chars, and list question

0 views
Skip to first unread message

digi....@gmail.com

unread,
Nov 27, 2006, 5:12:28 PM11/27/06
to
another simple exercise that i am trying to wrap my head around as i
learn prolog:

how would i convert the elements of a list from its ascii value to its
char value.
for example: [97,98,99,100 ] would become [a,b,c,d], if i had a set of
facts, charvalue(X,Y), where X is its ascii value and Y is its char
value?

another question i had is it possible to append lists to itself, i.e if
i had a list X = [1,2,3] and i wanted to append to it 4, is there
anyway to do append(X, 4, X), so that it would return the original list
X but with 4 added at the end?

because what i am trying to do is read in a text file character by
character and then append each character to a list called Word until it
reaches a space then append that list to a list called Lines and then
when it reaches a new line append that list Line to a list called Page,
but i am trouble updating the lists.

thanks in advanced.

digi....@gmail.com

unread,
Nov 27, 2006, 5:19:12 PM11/27/06
to
oh my code for my second prolem so far is the following:

get_text2(newPage) :-
open('myfile.txt', read, S, [alias(stream)]),
repeat,
get_code(stream, X),
(alphanum(X, Y) -> append(Word, Y, Word);
space(X) -> append(Line, Word, Line);
newline(X) -> append(Page, Line, Page);
X == -1),
X == -1,
close(stream).

Markus Triska

unread,
Nov 29, 2006, 2:56:50 PM11/29/06
to
digi....@gmail.com writes:

> how would i convert the elements of a list from its ascii value

%:- char_code(Char, 97).
%@% Char = a ;
%@% No more solutions.

> for example: [97,98,99,100 ] would become [a,b,c,d], if i had a set of

code_atom(Code, Atom) :- char_code(Atom, Code).

?- maplist(code_atom, [97,98,99,100], As).
%@% As = [a, b, c, d] ;
%@% No more solutions.

> i had a list X = [1,2,3] and i wanted to append to it 4, is there

append/3 describes a relation between 3 lists:

?- X = [1,2,3], append(X, [4], Y).
%@% X = [1, 2, 3]
%@% Y = [1, 2, 3, 4] ;
%@% No more solutions.

> then when it reaches a new line append that list Line to a list
> called Page,

For linear time, prepend new lines at the front, and in a final step
reverse the collection. Or use partially instantiated lists:

word(Word) :-
get_char(C),
( ( C == '\n' ; C == ' ' ; C == end_of_file) ->
Word = []
; Word = [C|Rest],
word(Rest)
).


words(Words) :-
( at_end_of_stream ->
Words = []
; word(W),
Words = [W|Rest],
words(Rest)
).

?- words(Ws).
|: these are the words
|: {CTRL+D}

Ws = [[t, h, e, s, e], [a, r, e], [t, h, e], [w, o, r, d, s]] ;

All the best,
Markus Triska

0 new messages