Re: testing keyboard input for a digit

Francois Berenger <[email protected]>
Newsgroups gmane.comp.lang.ocaml.beginners
Message-ID <[email protected]>
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.


------------------------------------

Archives up to December 31, 2011 are also downloadable at http://www.connettivo.net/cntprojects/ocaml_beginners
The archives of the very official ocaml list (the seniors' one) can be found at http://caml.inria.fr
Attachments are banned and you're asked to be polite, avoid flames etc.Yahoo! Groups Links

<*> To visit your group on the web, go to:
    http://groups.yahoo.com/group/ocaml_beginners/

<*> Your email settings:
    Individual Email | Traditional

<*> To change settings online go to:
    http://groups.yahoo.com/group/ocaml_beginners/join
    (Yahoo! ID required)

<*> To change settings via email:
    [email protected] 
    [email protected]

<*> To unsubscribe from this group, send an email to:
    [email protected]

<*> Your use of Yahoo! Groups is subject to:
    http://info.yahoo.com/legal/us/yahoo/utos/terms/
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.