zipWith
is a built-in method in Haskell that applies the function given as the first argument pairwise on each member of the two given lists.
Given two lists [, , , … , ] and [, , , … , ] and a function f, zipWith
does pairwise computations, as shown in Figure 1 below:
zipWith (function) list1 list2
The zipWith
method takes the following parameters:
function
: This parameter represents the operation that needs to be performed on each member of the two lists. This may be a simple operator (such as addition, subtraction, multiplication, or division) or a user-defined function.lists
Note: The list types in the
zipWith
method includeNumber
,String
, andByteString
. Therefore, the functions that are allowed will also vary. For instance, the function(++)
must be used to concatenate two strings.
(a -> b -> c) -> [a] -> [b] -> [c]
The zipWith
method returns a list that is of the same type as the input lists.
main :: IO ()-- Additionmain = print(zipWith (+) [0,1,2,3] [4,5,6,7]) >>-- Subtractionprint(zipWith (-) [2,2,8] [3,1,7]) >>-- Multiplicationprint(zipWith (*) [2,2,2] [3,2,1]) >>-- Divisionprint(zipWith (/) [20,5,8] [5,5,5])
main :: IO ()-- user-defined functionsmain = print(zipWith (\x y -> 3*x + y) [0,1,2,3] [4,5,6,7]) >>print(zipWith (\x y -> x `mod` y) [10,20,30] [2,5,6])
main :: IO ()-- stringsmain = print(zipWith (++) ["e","p","e","s"] ["d","r","s", "o"] ) >>print(zipWith (++) ["hello ", "this is "] ["world", "educative"])
zip
unzip
zipWith3
zip3
unzip3