Related Tags

zipwith
communitycreator

# What is zipWith in Haskell?

Imama Zahoor

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

### 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 [$x_{0}$, $x_{1}$, $x_{2}$, … , $x_{n}$] and [$y_{0}$, $y_{1}$, $y_{2}$, … , $y_{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 ()-- Additionmain = 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 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

• zip
• unzip
• zipWith3
• zip3
• unzip3

RELATED TAGS

zipwith
communitycreator

CONTRIBUTOR

Imama Zahoor