What is zipWith in Haskell?
Overview
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:
Syntax
zipWith (function) list1 list2
Parameters
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.- Two
lists
Note: The list types in the
zipWithmethod includeNumber,String, andByteString. Therefore, the functions that are allowed will also vary. For instance, the function(++)must be used to concatenate two strings.
Return type
(a -> b -> c) -> [a] -> [b] -> [c]
The zipWith method returns a list that is of the same type as the input lists.
Code example 1: Simple operators
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])
Code example 2: User-defined functions
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])
Code example 3: Other list types
main :: IO ()-- stringsmain = print(zipWith (++) ["e","p","e","s"] ["d","r","s", "o"] ) >>print(zipWith (++) ["hello ", "this is "] ["world", "educative"])
Related functions
zipunzipzipWith3zip3unzip3