summaryrefslogtreecommitdiff
path: root/read.prolog
blob: 63d3ae7f893fe17b8842f6e71621a7efc116b494 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

:- module(read, [prompt/1, readList/1]).


% functions for obtaining a line of input text and parsing
% it into a list of words

% prompt provides the user with a '>' prompt as well
% readList merely obtains and parses the input


prompt(L) :-
    write('> '),
    readList(L).


readList(L) :-
    readLine(X),
    wordList(L,X,[]), !.


readLine(L) :-
    get_char(C),
    readLine_tail(C,L).


readLine_tail('\n',[]) :- !.
readLine_tail(C,[C|X]) :-
    get_char(C2),
    readLine_tail(C2,X).


wordList(X) --> whitespace, wordList(X).
wordList([X]) --> word(X).
wordList([X]) --> word(X), whitespace.
wordList([X|Y]) --> word(X), whitespace, wordList(Y).


word(W) --> charList(X), {atom_chars(W,X)}.


charList([X|Xs]) --> char(X), charList(Xs).
charList([X]) --> char(X).


whitespace --> whsp, whitespace.
whitespace --> whsp.


whsp --> oneOf(_,[' ', '\r', '\n', '\t']).
char(X) --> noneOf(X,[' ', '\r', '\n', '\t']).


oneOf(X,L) --> [X], {member(X,L)}.
noneOf(X,L) --> [X], {not(member(X,L))}.