Converting Input to ASCII: Explanation of Prolog Code

I am trying to read and convert a string to an ASCII value using the Prolog predicate read_command/1.

The following code works. Can someone explain how to understand this code below?

<Preview> read_command (L): -% read_command / 1    get0 (C), read_command (_, L, C). read_command (_, [], X ): -% auxiliary predicate read_command / 3   member (the X, `\ n \ T`.),    ! . read_command (X, [C | L], C): -    get0 (C1), read_command (X, L, C1).
+4
source share
2 answers

read_command / 1 reads the first char available from the current input stream and uses it as a lookahead.

read_command / 3 just stops when the lookahead is a space or a period. Otherwise, put lookahead on the list, get a new look from the stream, and write it down.

I think the first sentence of read_command / 3 should also handle the case when X is -1, means the end of the file (for example, after pressing Ctrl + D)

+3
source

TL DR: Do not use get0/1!

get0/1considered obsolete , even by Prolog processors that implement it (for example, SWI).

Instead, use get_char/1and represent strings as not lists of characters like codelists!

< > read_command (Chars): -  get_char (),  read_command_aux (Chars, Next). read_command_aux (Chars, Char): -  member (Char, ['.', '\ t', '\n', end_of_file],  !,  Chars = []. read_command_aux ([Char | Chars], Char): -  get_char (),  read_command_aux (Chars, Next).

SWI-Prolog 7.3.15:

?- read_command(Chars).
|: abc
Chars = [a, b, c].

?- read_command(Chars).
|: abc.

Chars = [a, b, c].

?- read_command(Chars).
|: 123abc
Chars = ['1', '2', '3', a, b, c].

, :

< > ? - read_command (Chars), atom_chars (Command, Chars). |: abcd. Chars = [a, b, c, d], Command = abcd.

, , SWI, SICStus Prolog 4.3.2 ( ). ​​

+2

Source: https://habr.com/ru/post/1622634/


All Articles