How to resolve the algorithm Keyboard input/Obtain a Y or N response step by step in the Forth programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Keyboard input/Obtain a Y or N response step by step in the Forth programming language

Table of Contents

Problem Statement

Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need to press an   enter   key.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Keyboard input/Obtain a Y or N response step by step in the Forth programming language

Source code in the forth programming language

: flush ( -- )  \ discard pending input
  begin key? while key drop repeat ;

: y-or-n ( c-addr u -- f )
  flush begin
    cr 2dup type key bl or                  \ note 1.
    dup [char] y = swap [char] n = over or  \ note 2.
    if nip nip exit then
  drop again ;

\ Note 1. KEY BL OR returns a lowercase letter in the case that an
\ uppercase letter was entered, an unchanged lowercase letter in the
\ case that a lowercase letter was entered, and garbage otherwise.  BL
\ returns the ASCII code for a space, 32, which is incidentally the
\ "bit of difference" between ASCII uppercase and lowercase letters.

\ Note 2. this line has the stack effect ( x -- f1 f2 ), where F1 is
\ true only if x='y', and F2 is true only if x='y' OR if x='n'.

\ I think these expressions aren't too clever, but they _are_ rather
\ optimized for the task at hand.  This might be more conventional:

: y-or-n ( c-addr u -- f )
  flush begin
    cr 2dup type key case
      [char] y of 2drop true  exit endof
      [char] Y of 2drop true  exit endof
      [char] n of 2drop false exit endof
      [char] N of 2drop false exit endof
  endcase again ;


  

You may also check:How to resolve the algorithm 2048 step by step in the Visual Basic .NET programming language
You may also check:How to resolve the algorithm Dot product step by step in the Icon and Unicon programming language
You may also check:How to resolve the algorithm Case-sensitivity of identifiers step by step in the Euphoria programming language
You may also check:How to resolve the algorithm 4-rings or 4-squares puzzle step by step in the Go programming language
You may also check:How to resolve the algorithm Euler's sum of powers conjecture step by step in the Pascal programming language