-2

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";;


Mar Cial R
  • 936
  • 9
  • 20

1 Answers1

1

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.

Yawar
  • 11,272
  • 4
  • 48
  • 80
  • Thanks for your answer!!! There are more questions! how can i zip function apply n-list?? i want to zip like this zip [1;2;3;] [4;5;6] [7;8;9] -> [1;4;7;2;5;8;3;6;9] like this. – Cyber0946 Mar 25 '20 at 05:27
  • You will need to write a function `zip3` that takes three arguments. Generally for _n_ parameters you will need a separate function `zipN`. – Yawar Mar 25 '20 at 13:28
  • I want to make N_ary zip function but i stuck in trouble with pattern matching.ㅠㅠ input is a lists of list and output is list Like [[1;2;3];[4;5;6];[7;8]] ->[1;4;7;2;5;8;3;6] – Cyber0946 Mar 25 '20 at 15:24
  • let nzip lst = match with lst <———how can i pattern match n-ary list???? – Cyber0946 Mar 25 '20 at 15:29
  • @Cyber0946 you can pattern match against an n-ary list just like any list: with a base case (empty list) and an inductive case (list head and tail). But the main problem you will face is outputting zipped tuples of arbitrary size depending on the number of input lists. Tuples are static in size so there's no way (that I know) to do that [with a single function]. – Yawar Mar 27 '20 at 20:16
  • Btw I'm assuming you want to output tuples like `[(1, 4, 7); (2, 5, 8)]`, not lists like `[1; 4; 7; 2; 5; 8; 3; 6]`. Zipping lists together means outputting a list of tuples; it doesn't make sense to output a flat list from a zip operation. – Yawar Mar 27 '20 at 20:17