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 [x0x_{0}, x1x_{1}, x2x_{2}, … , xnx_{n}] and [y0y_{0}, y1y_{1}, y2y_{2}, … , yny_{n}] and a function f, zipWith does pairwise computations, as shown in Figure 1 below:

Figure 1

Syntax

zipWith (function) list1 list2

Parameters

The zipWith method takes the following parameters:

  1. 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.
  2. Two lists

Note: The list types in the zipWith method include Number, String, and ByteString. 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 ()
-- Addition
main = print(zipWith (+) [0,1,2,3] [4,5,6,7]) >>
-- Subtraction
print(zipWith (-) [2,2,8] [3,1,7]) >>
-- Multiplication
print(zipWith (*) [2,2,2] [3,2,1]) >>
-- Division
print(zipWith (/) [20,5,8] [5,5,5])

Code example 2: User-defined functions

main :: IO ()
-- user-defined functions
main = 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 ()
-- strings
main = print(zipWith (++) ["e","p","e","s"] ["d","r","s", "o"] ) >>
print(zipWith (++) ["hello ", "this is "] ["world", "educative"])

Related functions

  • zip
  • unzip
  • zipWith3
  • zip3
  • unzip3

Free Resources