Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Prelude have same functions with just different args?

Tags:

haskell

Consider functions from Prelude like zipWith. There are other functions like zipWith3 ... zipWith7 which differs only by number of arguments. There are many similar examples, in other languages too (scala, ocaml).

What are reasons for creating functions with particular number of elements? Why not use generalized version? Maybe derive particular zipWith from number of applied arguments

like image 456
sigrlami Avatar asked Nov 29 '22 07:11

sigrlami


1 Answers

The generalized version of zipWith does exist: it's the ZipList applicative functor:

import Control.Applicative

zipWith  f a1 a2 = getZipList (f <$> ZipList a1 <*> ZipList a2)
zipWith3 f a1 a2 a3 = getZipList (f <$> ZipList a1 <*> ZipList a2 <*> ZipList a3)

And so on. The thing is, it's generally just quicker to use the zipWithN functions that to wrap everything with a ZipList constructor.


EDIT: chi's comment points out that I wasn't as clear as I should have been. The point was that the ZipList wrapper allows us to use the applicative f <$> x1 <*> ... <*> xn idiom to zip any number of lists whose element types are compatible with f's type.

like image 85
Luis Casillas Avatar answered Dec 09 '22 13:12

Luis Casillas