PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, April 27, 2022

[FIXED] how to get rid of the warning "this pattern-matching is not exhaustive..."?

 April 27, 2022     function, ocaml, warnings     No comments   

Issue

I wrote the following function in OCaml that takes a nested Pair and returns a Pair(a,b) so that a is a nested Pair of all the odd elements and b is a nested Pair with all the even elements:

let rec split_var_val xs =
  match xs with
  | Nil -> Pair(Nil,Nil)
  | Pair(Pair(x, Pair(y, Nil)), tail) ->
      let Pair(a,b) = split_var_val tail in
      Pair(Pair(x,a),Pair(y,b)) 
  | _ -> raise X_no_match ;;

the function works well but I am getting the following warning:

this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(Nil|Bool _|Number _|Char _|String _|Symbol _)

how can I fix the function to get rid of the warning?


Solution

The warning is produced by this expression:

let Pair(a,b) = split_var_val tail in

which assumes that split_var_val is always returning a value constructed with the Pair constructor, which is a fair assumption if we will look into the implementation (modulo the all-matching case that raises an exception).

If you would like to make this assumption you can either tell the compiler to hush, e.g.,

let Pair(a,b) = split_var_val tail [@@warning "-P"] in

or you can actually make the pattern match exhaustive, by matching on all cases,

let (a,b) = match split_var_val tail with
  | Pair (a,b) -> (a,b)
  | _ -> assert false in (* or something less generic *)

A better solution would be to rework your function and make it return a pair without wrapping it into the Pair constructor. (Basically, wrapping it with Pair is the same as premature upcasting), e.g.

let rec split_var_val xs =
  match xs with
  | Nil -> (Nil,Nil)
  | Pair(Pair(x, Pair(y, Nil)), tail) ->
      let (a,b) = split_var_val tail in
      (Pair(x,a),Pair(y,b)) 
  | _ -> raise X_no_match 

and then, in the other places where you were using split_var_val xs you will just need to wrap it back as let x,y = split_var_val xs in Pair (x,y)



Answered By - ivg
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing