如何逃脱OCaml中的特殊角色?

时间:2018-03-11 06:58:44

标签: pattern-matching ocaml

我在OCaml中使用模式匹配来检查字符串中的有效字符,如果将\0传递给模式匹配函数,它会在屏幕上打印一条消息发现了这个字符串。

let my_fun char = 
    match char with
      'a' .. 'z' -> Printf.printf ("Valid ALPHA found: %c\n") char;
    | 'A' .. 'Z' -> Printf.printf ("Valid ALPHA found: %c\n") char;
    | ' ' -> Printf.printf ("WHITE_SPACE found\n");
    | '\0' -> Printf.printf("End of string reached\n"); (* The backslash isn't escaped *)
    | _ -> Printf.printf ("Invalid Token found\n"); 
 ;;

编译器给出错误:

 Error: Illegal backslash escape in string or character (\0)

如何逃避\或检查空终结符/换行符是否已传入my_fun中的OCaml

1 个答案:

答案 0 :(得分:2)

您可以改为使用Char.chr(0),或只使用'\000'

- 修复 - Char.chr(0)确实不起作用 - 我想这是因为它不被视为常数。

'\ 000'确实有效。

let my_fun char = 
    match char with
      'a' .. 'z' -> Printf.printf ("Valid ALPHA found: %c\n") char;
    | 'A' .. 'Z' -> Printf.printf ("Valid ALPHA found: %c\n") char;
    | ' ' -> Printf.printf ("WHITE_SPACE found\n");
    | '\000' -> Printf.printf("End of string reached\n"); (* The backslash isn't escaped *)
    | _ -> Printf.printf ("Invalid Token found\n"); 
 ;;
let a = Char.chr(0);;
my_fun a;;

将提供:

utop # my_fun a;;
End of string reached
- : unit = ()