简体   繁体   中英

OCaml list types behavior

Following the chapter of Real World OCaml on error handling , it is permissible to construct a list as such:

utop # [ Ok 3; Error "abject failure"; Ok 4] ;;                           
- : (int, string) Result.t list = [Ok 3; Error "object failure"; Ok 4]

I have read in this text and in others, however, that "all elements of a list must be of the same type."

Then what exactly is the type (int, string) Result.t ? As far as I can tell, this is permissible because both Ok and Error are of the same type Result.t . The tuple-like notation of (int, string) , however, is confusing to me, and if the above is acceptable, why isn't something like this fine as well:

utop # [ Ok 3; Error "abject failure"; Ok "asdf"] ;;              
325 Error: This expression has type string but an expression was expected of type
             int

Result.t is a parameterized type. That is, it takes two types and forms them into a new type. This is the same as the way that list takes one type and forms it into a new type.

The type of [3; 4; 5] [3; 4; 5] [3; 4; 5] is int list . That is, it's a list whose elements are ints.

In the same way, the type (int, string) Result.t is a result whose good values are given by ints and whose errors are given by strings.

For a given choice of types for a and b, values like Ok a and Error b are indeed the same type. This is a little bit like the way that Some 3 and None are the same type.

Note that Result.t only takes two types, one for the good results and one for the errors. The problem with your last example is that you're using two different types for your good results.

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