0

I'm using a predicate to read some values in consecutive prompts in a prolog program shell, and I want the user to be able to get a help message when asked for input. The scenario would be:

  1. Ask for input
  2. If input = 'help', display help message and ask for the same input again
  3. If input /= 'help', assign Value and leave successfully

What I've done so far:

ask_input( Question, Value ) :-
    write( Question ), % Please enter  ... :
    read( ReadValue ),
    ( ReadValue = 'help' ->
        write( 'Help message...' ),
        ask_input( Question, Value )
    ;   Value = ReadValue
    ).

Obviously, the code above does not work. It will fail on the ask_input inside the condition.

Community
  • 1
  • 1
vmassuchetto
  • 1,529
  • 1
  • 20
  • 44

1 Answers1

0

I did this, and it seems to work:

ask_question( Question, Value ) :-
    write( Question ), nl,
    read( ReadValue ),
    ask_question2( Question, ReadValue, NewValue ),
    Value = NewValue.

ask_question2( Question, ReadValue, NewValue ) :-
    ReadValue = 'help',
    write( 'Help message ...' ), nl,
    ask_question( Question, NewValue ).

ask_question2( _, Value, Value ).
vmassuchetto
  • 1,529
  • 1
  • 20
  • 44
  • I'd write `ask_question2(Question, help, NewValue) :-` and then remove the `ReadValue = 'help'` line. – Daniel Lyons Oct 16 '12 at 15:50
  • 2
    Note that the second clause of ask_question2/3 will succeed for ReadValue = 'help' upon backtracking. – gusbro Oct 16 '12 at 17:43
  • More I think about, the more I think this approach could be simplified and the problem avoided by taking the input and then handling it. The 'help' functionality would just be one handler. The default handler would be to display an error and possibly the 'help' message. Build your input loop around that instead of trying to handle invalid input and help at the deeper level. – Daniel Lyons Oct 16 '12 at 18:02