'Pattern matching in OCaml

I have an OCaml list of the type (string*int) list. I have to traverse through the list and check for the int value. If for all the elements in my list, the property int>=0 holds, then the list is "fine", else, if it fails at any one instance, then I have to return "fail". For this, I made the following attempt

let rec check tlist = 
  match tlist with
    [] -> print_string "finished"
  | (s, i)::tail -> 
    if i < 0 then print_string "fail" 
    else check tail 

on running this from the interpreter, I receive a warning that the pattern matching is not exhaustive. Also, when I run it in the following input types

let z = [("ask", 1); ("tell", 2); ("three", 3); ("goal", -4)] ;;

it returns fail as expected but for

let z = [("ask", 1); ("tell", 2); ("three", 3); ("goal", 4)] ;; ,

it returns Exception:

Match_failure ("//toplevel//", 7, -22).

How to go about this?

Edit: Also, there is another part to the problem. I have to ensure that the string s is not repeated in the list. How to go about that?



Solution 1:[1]

The code you post is fine, does not generate any warning, and work for the input you say.

If you want to improve it, you should try to separate the algorithm logic and input/output to have something more flexible: have your function return a boolean instead of unit.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gasche