In: Computer Science
Create a F# Function.
Function Signature: zip L1 L2
The function zip combines the elements of two lists pairwise,
resulting in a list of tuples, where the first tuple in the list
contains the first element of L1 as the first element, and the
first element of L2 as the second element
// // zip L1 L2
// // Zip two lists
// // Returns list of tuples
// // Examples:
// zip [] [] => []
// zip [1] [1] => [(1, 1)]
// zip [1; 2; 40] [3; 56; 6] => [(1, 3); (2, 56); (40, 6)]
// zip [1; 2; 3] ['a'; 'b'; 'c'] => [(1, 'a'); (2, 'b'); (3,
'c')]
Code: if inbuilt zip function is not to be used and need to make a zip function
let rec zip(list1:'list1 list, list2:'list2 list) : list<'list1 * 'list2> =
// stoping condition for recursive call
if List.length list1 = 1 then [List.head list1 , List.head list2]
// continue the recursive call if the length > 1
else (List.head list1, List.head list2) :: zip (List.tail list1 , List.tail list2)
let list1 = [1; 2; 3]
let list2 = ['a'; 'b'; 'c']
// if both the list are empty
if list1.IsEmpty then
let zippedlist = []
printf "%A, %A => %A\n" list1 list2 zippedlist
//if there is some content in the list
else
let zippedlist = zip(list1, list2)
printf "%A, %A => %A\n" list1 list2 zippedlist
Try the code for different values of list1 and list2
Code;: if inbuilt zip function can be used
let zip list1 list2 =
List.zip list1 list2
let list1 = [1; 2; 3]
let list2 = ['a'; 'b'; 'c']
// if both the list are empty
if list1.IsEmpty then
let zippedlist = []
printf "%A, %A => %A\n" list1 list2 zippedlist
//if there is some content in the list
else
let zippedlist = zip list1 list2
printf "%A, %A => %A\n" list1 list2 zippedlist
Output:
Explaination:
Firstly check if the list has some contents or not if no content i.e if list.IsEmpty = true then we can print the empty list else we go to the zip function
Zip function is a recursive function which every time takes element at the Head position of both the list and insert it as a tuple in the resulting list