OCaml Option get

后端 未结 3 1349
不知归路
不知归路 2021-02-14 07:06

I\'m new to OCaml, I\'m trying to understand how you\'re supposed to get the value from an \'a option. According to the doc at http://ocaml-lib.sourceforge.net/doc/Option.html,

相关标签:
3条回答
  • 2021-02-14 07:27

    You should listen to the above posters advice regarding type safety but also be aware that unsafe function such as Option.get (which is available in batteries btw) are usually suffixed with exn. If you're curious this is how Option.get or Option.get_exn could be implemented then:

    let get_exn = function
      | Some x -> x
      | None   -> raise (Invalid_argument "Option.get")
    
    0 讨论(0)
  • 2021-02-14 07:32

    The usual way to do this is with pattern matching.

    # let x = Some 4;;
    val x : int option = Some 4
    
    # match x with
      | None -> Printf.printf "saw nothing at all\n"
      | Some v -> Printf.printf "saw %d\n" v;;
    saw 4
    - : unit = ()
    

    You can write your own get function (though you have to decide what you want to do when the value is None).

    0 讨论(0)
  • 2021-02-14 07:33

    The traditional way to obtain the value inside any kind of constructor in OCaml is with pattern-matching. Pattern-matching is the part of OCaml that may be most different from what you have already seen in other languages, so I would recommend that you do not just write programs the way you are used to (for instance circumventing the problem with ocaml-lib) but instead try it and see if you like it.

    let contents = 
       match z with
       Some c -> c;;
    

    Variable contents is assigned 3, but you get a warning:

    Warning 8: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: None

    In the general case, you won't know that the expression you want to look inside is necessarily a Some c. The reason an option type was chosen is usually that sometimes that value can be None. Here the compiler is reminding you that you are not handling one of the possible cases.

    You can pattern-match “in depth” and the compiler will still check for exhaustivity. Consider this function that takes an (int option) option:

    let f x =
      match x with
      Some (Some c) -> c
      | None -> 0
      ;;
    

    Here you forgot the case Some (None) and the compiler tells you so:

    Warning 8: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: Some None

    0 讨论(0)
提交回复
热议问题