I wrote this code, as a novice a to Prolog, for a challenge posted on /r/DailyProgrammer. The formal description of this challenge, as presented in the prompt reads:
Input description
On console input you will be given a variable number of 0's and 1's that correspond to letters in the alphabet [a-z] and whitespace ' '. These will be integers coming in, it's your job to cast them however you need.
Output description
The program should output the english translation (or other languages if you feel so inclined!) of the binary phrase
This is a fairly simple task so, even as a novice to Prolog, it didn't take me long to complete.
main(Words):-
open('text.txt',read,Stream),
readAll(Stream,Codes),
close(Stream),
atom_codes(Words,Codes).
readAll(Stream,[]):-
at_end_of_stream(Stream).
readAll(Stream,Out):-
readBinary(Stream,8,Out2),
readAll(Stream,Out3),
Out = .(Out2,Out3).
readBinary(_,0,0).
readBinary(Stream,Digits,Out):-
get_code(Stream,A),
B is (A-48) * 2 ^ (Digits-1),
Digits2 is Digits - 1,
readBinary(Stream,Digits2,Out2),
Out is B + Out2.
text.txt
is a text file containing the flowing binary digits encoded as characters in UTF-8:
0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100
Running the code results in the correct output:
Hello World
The code undoubtedly works, and I even find that I like how it looks. My greatest concern, however, is that this somehow does not maintain style and format standards of Prolog programs. Reading through the code, it reads as a completely imperative program, but I know that Prolog is built off the logic programming paradigm. Is this because of a fault in how I wrote the program, or is the problem that this challenge does not lend itself to logic programming? If the former is correct, how could this be written to better reflect the full capabilities of Prolog?