#Use zip
Use zip
Often you need to map over a list and apply some function which depends on the index of the argument in the list. while a lot of impure languages who have some sort of map
builtin have the index be an optional argument, this is impossible in Haskell. instead, use:
mapWithIndex f xs === f<$>zip[0..]xs
=== [f i x|(i,x)<-zip[0..]xs] {- inlinable version -}
=== zipWith f[0..]xs
mapWithIndex f === (f<$>).zip[0..] {- points free version -}
(This also gives us 1-based indexing for free!)
Often this combines well within list comprehensions, where even a builtin mapWithIndex
won't help:
[ ... | ..., (i,x)<-zip[0..]xs, ...]
Other times, you really want to use the nonexistant equivalent maximumOn
of sortOn
, but the import is too many bytes, or using maximumBy
is too many bytes too. instead, use*:
sortOn f xs === snd$sort$(f>>=(,))<$>xs
=== snd$sort[(f x,x)|x<-xs] {- inlinable version -}
sortOn f === snd.sort.(f>>=(,)<$>) {- points free version -}
Note that sometimes you will need both the best x
and its f x
, in which case you can get rid of three bytes and have it computed for you for free!
many other uses for this combination are possible too.