简体   繁体   中英

Ocaml: how to use a variant type as return value

I have a variant type named response that is based on another variant type. But I am unable to use the response variant type as a return value. Here is the code :

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

I have created a 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

And when I try to compile it I have the following error:

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 has type ack_error * int * string * string , not response . You just need to wrap it with the Error constructor:

let parse_response mpd_response =
  if mpd_response = "OK\n" then Ok
  else Error (parse_error_response mpd_response)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM