Warning 8: Incomplete pattern matching warning in let statement

I often do pattern matching in a let expression, where I know the result form. It is clear that I cannot expect the compiler to derive this knowledge at all, but perhaps there is a more idiomatic way to do this in a condensed form.

As an example, please check out the following code:

type foo = A of int | B of string
let x = (true, A 0)
let (b, A i) = x in i + 2 

Which correctly warns me that the result (_, B _)does not match. A possible way is to explicitly handle the missing case, as in:

let (b,i)  = match x with 
    | (a, A j) -> (a,j+2)
    | _ -> failwith "implementation error!" 

But this obscures the actual calculation. Is there a shorter option?

Edit: Jeffrey Scofield noted that in the case without nesting, the explicit conversion function works well. Is there also a version for nested type matching?

+4
3

, , OCaml 4.02 , [@@warning "-8"] .

. OCaml.

OCaml ( ) , .

" ", , ( )... - (, , ).

+6

, List.hd.

let int_of_foo = function
   | A i -> i
   | _ -> raise (Invalid_argument "int_of_foo")

let string_of_foo = function
   | B s -> s
   | _ -> raise (Invalid_argument "string_of_foo")

let (_, f) = x in int_of_foo f + 2

( ) :

int_of_foo (snd x) + 2

( x , .)

+4

Often you can do this without approval (i.e. check your code at compile time) if you use a polymorphic option instead, like

type foo = [`A of int | `B of string]
let x = (true, `A 0)
let (b, `A i) = x in i + 2
+1
source

Source: https://habr.com/ru/post/1584052/


All Articles