Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Second match block not executing (OCaml)

Hey I’m new to ocaml and was trying out some of the exercises in a dune build. I think my issue is due to the semicolons but I’m not really sure. When running the following code:

let somelist = [1;2;3;4] in
  (* last element in a list *)
    match (last somelist) with
    | Some (v) -> 
      print_endline "last value of list:" ;
      print_int v;
    | None -> () ;
    
    print_newline ();

    (* last 2 elements in a list *)
    match (last_two somelist) with
    | Some (a::b) ->
      print_endline "last 2 elements in list: \n";
      print_int a;
      print_int (List.hd b);
    | None -> () ;
    | Some ([]) -> () ;;

print_newline () ;;

it only prints out:

last value of list: 
4

instead of continuing and printing out the last 2 elements in the list afterwards. I tested out the other 2 functions, last and last_two in utop and they seem to work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I wanted it to print out:

last value of list:
4
last 2 elements in list: 
3 4

>Solution :

Each branch of a match contains a list of expressions separated by ; (or at least this is one way to describe the syntax). So your second match is contained within just one of the branches of the first match. I.e., it executes only if last somelist is None.

The usual way to solve this is by enclosing the first match in begin / end or parentheses. Here’s one way to do this:

begin
match (last somelist) with
| Some (v) -> 
  print_endline "last value of list:" ;
  print_int v;
| None -> ()
end;

print_newline ();

match (last_two somelist) with
.  .  .
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading