Loading ...
Sorry, an error occurred while loading the content.

13970Re: "ocaml_beginners"::[] testing keyboard input for a digit

Expand Messages
  • Francois Berenger
    Oct 23, 2013
      On 10/24/2013 08:35 AM, Jean Saint-Remy wrote:
      > Hi,
      >
      > I am trying to test user's input to see if it contains a digit, but it
      > is not going so well
      >
      > let rec kbd () =
      > let ls = [0;1;2;3;4;5;6;7;8;9;] (* there doesn't seem to be a way of
      > expressing a range 0..9 *)

      Consider using the batteries included library for any real project.

      http://ocaml-batteries-team.github.io/batteries-included/hdoc2/

      > let rec find test = function
      > | [] -> raise Not_found
      > | hd :: tl -> if test hd then hd else find test tl in
      > print_string "Please enter an item number: ";
      > try
      > let item = read_line () in
      > if (item = find ls) then failwith "an item should contain a
      > digit ";
      > item
      > with Failure msg -> (print_endline (msg ^ ", try again"); kbd ()) ;;
      >
      > -: Error This expr "ls" has type int list but an expression was expected
      > of type 'a -> bool
      >
      > Thank you for any suggestion

      You can use Scanf.sscanf to convert a string to a number.

      http://ocaml-batteries-team.github.io/batteries-included/hdoc2/BatScanf.html

      You can catch the scan failure to ask the user to try again.

      Here are some trials in the toplevel:

      let item = "10" in
      Scanf.sscanf item "%d" (fun i -> i);;

      let item = "toto" in
      Scanf.sscanf item "%d" (fun i -> i);;
      Exception:
      Scanf.Scan_failure
      "scanf: bad input at char number 0: ``character 't' is not a decimal
      digit''".

      Have fun,
      F.

      > jean
      >
      >


      --
      Best regards,
      Francois Berenger.
    • Show all 2 messages in this topic