Cyber0946
Cyber0946

Reputation: 1

Ocaml syntax error : pattern expected in building zip fuction

I want to make fuction called zip so:
zip [1;2;3;4] [5;6;7;8] would produce: [1;5;2;6;3;7;4;8]

but I'm getting an error: line#4 h2::t2 make error syntax error : pattern expected

What would be the correct syntax?

let rec zip lst1 lst2 =
    match lst1 lst2  with
    | [] [] -> []
    | h1::t1 h2::t2 -> h1 h2::zip t1 t2                         
    |_ _ -> failwith "The lists seems to have different lengths";;


Upvotes: -2

Views: 236

Answers (1)

Yawar
Yawar

Reputation: 11607

A pattern match can match against only one expression at a time. If you want to match against two lists i.e. two expressions, you will want to combine them into a single expression. The idiomatic way to do this is to pair them up using a tuple, e.g.:

match lst1, lst2 with
| [], [] -> []
| h1::t1, h2::t2 -> (h1, h2)::(zip t1 t2)
| _ -> failwith "Cannot zip lists of different lengths"

The syntax for putting expressions in a tuple technically is (e1, e2, ..., en); but when it is unambiguous e.g. when surrounded by other symbols or keywords that take precedence, OCaml allows leaving out the parentheses and just using the commas.

Upvotes: 1

Related Questions