OCaml - 通过stdin stdout输入,显示,验证枚举类型

时间:2014-01-07 00:13:14

标签: ocaml

枚举类型数据:

type sex = | M | F | Undef;;

我想知道在控制台程序中输入和验证枚举类型数据的首选'OCaml'方式是什么?我尝试编写下面的程序,我确定我正确显示枚举类型,但我不确定while循环中的验证是否正确。基本上我希望while循环内容提示用户输入枚举类型的有效数据并显示输入的值然后退出循环或失败并显示消息并重新提示用户输入有效数据。

type sex = | M | F | Undef;;
type loop = | Yes | No;;

let match_sex s str =
    match s with
    | M -> print_endline "Male"
    | F -> print_endline "Female"
    | Undef ->
            Printf.fprintf stdout "You entered '%s'. Please enter single character(M\\F)\n" str;;

let looping = ref Yes;;

while !looping = Yes do
    let s = looping := No; print_string "Enter sex(M\\F)->"; read_line() in
    let c = Char.uppercase s.[0] in
    let ans =
        match (c, String.length s) with
        | 'M', 1 -> M
        | 'F', 1 -> F
        | _ -> looping := Yes; Undef in match_sex ans s
done;;

提前感谢任何建议或意见。

2 个答案:

答案 0 :(得分:1)

就个人而言,我只是做

type sex = M | F

let rec prompt () =
  let input =
    print_string "Enter sex(M\\F)->";
    read_line() in
  match String.uppercase input with
  | "M" -> print_endline "Male"; M
  | "F" -> print_endline "Female"; F
  | bad_input ->
    Printf.printf "You entered '%s'. Please enter single character(M\\F)\n" bad_input;
    prompt ()

几点:

  • 更喜欢递归而不是循环
  • 额外的功能在这里买不到你所以我摆脱它
  • 我删除了Undef性,因为它永远不会被退回。
  • Printf.printf超过Printf.fprintf stdout

答案 1 :(得分:0)

type sex = | Male | Female;;

let match_sex sx =
    match sx with
    | Male -> "Male"
    | Female -> "Female";;

let rec get_sex() =
    let str = print_string "Enter sex(M/F)->"; read_line() in
    match Char.uppercase (str.[0]), String.length str with
    | 'M', 1 -> Male
    | 'F', 1 -> Female
    | undef_sex ->
            Printf.fprintf stdout "Your entry '%s' was invalid. Please try again.\n" str; get_sex();;

Printf.fprintf stdout "Your sex is->%s\n" (match_sex (get_sex()));;

这是我最终解决的问题。谢谢rgrinberg