Search code examples
prolog

How to write in a file N times in Prolog?


I am trying to write in a file N times in Prolog. I came up with this solution:

response(M,Out,N) :-
   write('How do you feel ?'),
   open('output.txt',write,Out),
   read(M),
   write(Out,M),
   close(Out),
   response(M,Out,S),
   S is N - 1.
response(M,Out,0).

The basic idea is to read an emotion from keyboard and write it into a file called output.txt. It gives me this error:

ERROR: Uninstantiated argument expected, found <stream>(0x60000311fb00) (stream-argument)
ERROR: In:
ERROR:   [12] open('/Users/dylan/Desktop/output.txt',write,<stream>(0x60000311fb00))
ERROR:   [11] response(sad,<stream>(0x60000311fb00),_10234) at /Users/dylan/Desktop/suggestsong.pl:14
ERROR:   [10] response(sad,<stream>(0x60000311fb00),3) at /Users/dylan/Desktop/suggestsong.pl:18
ERROR:    [9] toplevel_call(user:user: ...) at /Applications/SWI-   Prolog.app/Contents/swipl/boot/toplevel.pl:1158
Exception: (11) response(sad, <stream>(0x60000311fb00), _9654) ? creep
Exception: (10) response(_9306, _9308, 3) ? creep

Thw predicate without the loop works fine, but it's just one time reading and is not good for the purpose.

Can please someone help me ? Thank you all.


Solution

  • Thanks for the solution!

    I actually found also another simple way to solve this, using recursion:

    % chat with user 
    chat :-
      ask("y").
    
    
    ask("y") :-
       write('How do you feel?: '),
       read_string(user, "\n", "\r", End, E),
       %assert(emotion(E)), %assert a fact or rule into database
       suggest(emotion(E)),
       write("Continue: (y or n) "),
       read_string(user, "\n", "\r", End, Respond),
       ask(Respond).
    
    
    % The user type "n", hence computing and writing results into file
    ask("n") :- 
      tell('output.txt'), 
      %listing(emotion/1), 
      listing(genre/2),  %lookup result of genre/2 into database
      told.