1
votes
let disting v =
  match v with
  | int -> (*expression1*)
  | bool -> (*expression2*)
  | _ -> (*expression3*)

Whenever I run the code, disting true and disting false also turns out expression1. The result is vice versa with this code

let disting v =
  match v with
  | bool -> (*expression2*)
  | int -> (*expression1*)    
  | _ -> (*expression3*)

This one also have similar problem. How can I get the result I want?

2

2 Answers

5
votes

Pattern-matching does not work like you think it does.

It allows you to match expressions with values or pattern of values like in the following:

match some_int with
| 1  -> 1 
| 10 -> 2
| x  -> x/2   (* this matches any possible int, and it gives it the name 'x' for the rest *)

So here you will always match your first case because it does not filter anything. What you're saying is : match v with anything and let's call it 'bool' in the rest.

you may then try something like

let disting v =
  match v with
  | true -> (*expression2*)
  | 2 -> (*expression1*)    
  | _ -> (*expression3*)

which does not typecheck in OCaml as 'v' is either an int or a bool but can't be both. I dont know what you're trying to do but you should read some basis about the langage.

3
votes

The way to do it in Ocaml is to use sum types :

       type i_or_b = I of int | B of bool;
       let disting v =
         match v with
         | I x -> Printf.printf "v = I %d\n" x
         | B x -> Printf.printf "v = B %s\n" (string_of_bool x)