Problem Statement:
Zip two lists of Integers.
If the lists are of unequal length, return None
; otherwise return Some of (int*int) list
.
Solution:
Following naïve solution recurses over elements of the lists, and creates tuple, as part of the zip operation. If both lists are empty, it returns Some []
.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let rec zipTwo (x:int list) (y: int list) : ((int*int) list) option = | |
match x,y with | |
| ([], []) -> Some [] | |
| (xhd::xtl, yhd::ytl) -> | |
match zipTwo xtl ytl with | |
| None -> None | |
| Some lst -> Some ((xhd,yhd)::lst) | |
| (_,_) -> None |
The unequal length case is handled by the pattern outlined in line 8 , which simply returns None
. Subsequent return calls of the recursion detect it and simply return None
.
Thus, resultant signature of zipTwo
is given by:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val zipTwo : x:int list -> y:int list -> (int * int) list option |
Output:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> zipTwo [] [];; | |
val it : (int * int) list option = Some [] | |
> zipTwo [1;2] [2;4;8];; | |
val it : (int * int) list option = None | |
> zipTwo [1;2;3] [2;4;8];; | |
val it : (int * int) list option = Some [(1, 2); (2, 4); (3, 8)] |