Ocaml:如何使用变体类型作为 return 值
Ocaml: how to use a variant type as return value
我有一个名为 response 的变体类型,它基于另一个变体类型。但是我无法将 response 变体类型用作 return 值。这是代码:
type ack_error =
| Not_list
| Arg
| Password
| Permission
| Unknown
| No_exist
| Playlist_max
| System
| Playlist_load
| Update_already
| Player_sync
| Exist
type response = Ok | Error of ack_error * int * string * string
(* some code for the function_parse_error_response which signature is :
* str -> (ack_error * int * string * string)
*)
let parse_response mpd_response =
if mpd_response = "OK\n" then Ok
else parse_error_response mpd_response
我创建了一个 test.ml :
(* ocamlfind ocamlc -o test -package oUnit -linkpkg -g mpd.ml test.ml *)
open OUnit2
let test_ok test_ctxt = assert_equal Ok Mpd.parse_response "OK\n"
let mpd_tests =
"mpd_tests" >:::
["test OK" >:: test_ok]
let () =
run_test_tt_main mpd_tests
当我尝试编译它时出现以下错误:
ocamlfind ocamlc -o test -package oUnit -linkpkg -g mpd.ml test.ml
File "mpd.ml", line 84, characters 7-40:
Error: This expression has type ack_error * int * string * string
but an expression was expected of type response
parse_error_response mpd_response
的类型为 ack_error * int * string * string
,而不是 response
。你只需要用 Error
构造函数包装它:
let parse_response mpd_response =
if mpd_response = "OK\n" then Ok
else Error (parse_error_response mpd_response)
我有一个名为 response 的变体类型,它基于另一个变体类型。但是我无法将 response 变体类型用作 return 值。这是代码:
type ack_error =
| Not_list
| Arg
| Password
| Permission
| Unknown
| No_exist
| Playlist_max
| System
| Playlist_load
| Update_already
| Player_sync
| Exist
type response = Ok | Error of ack_error * int * string * string
(* some code for the function_parse_error_response which signature is :
* str -> (ack_error * int * string * string)
*)
let parse_response mpd_response =
if mpd_response = "OK\n" then Ok
else parse_error_response mpd_response
我创建了一个 test.ml :
(* ocamlfind ocamlc -o test -package oUnit -linkpkg -g mpd.ml test.ml *)
open OUnit2
let test_ok test_ctxt = assert_equal Ok Mpd.parse_response "OK\n"
let mpd_tests =
"mpd_tests" >:::
["test OK" >:: test_ok]
let () =
run_test_tt_main mpd_tests
当我尝试编译它时出现以下错误:
ocamlfind ocamlc -o test -package oUnit -linkpkg -g mpd.ml test.ml
File "mpd.ml", line 84, characters 7-40:
Error: This expression has type ack_error * int * string * string
but an expression was expected of type response
parse_error_response mpd_response
的类型为 ack_error * int * string * string
,而不是 response
。你只需要用 Error
构造函数包装它:
let parse_response mpd_response =
if mpd_response = "OK\n" then Ok
else Error (parse_error_response mpd_response)