haskellziplist-comprehensionpointfreecombinators

Haskell map/zip Vs. list comprehension


Which of the following are you most likely to write?

r = zip xs $ map sqrt xs

or

r = [(x, sqrt x) | x <- xs]

Sample code on the Internet seems to indicate that the former is more abundant and the preferred way.


Solution

  • I'd likely write

    map (\x -> (x, sqrt x)) xs
    

    If you prefer point-free, the above is equivalent to (after having imported Control.Monad and Control.Monad.Instances)

    map (ap (,) sqrt) xs
    

    Another alternative that hasn't yet been mentioned is

    zipWith (,) xs (map sqrt xs)