10 ways to map a list in haskell

Haskell is such a cool language
10 ways to map a list in haskell
By Atticus Kuhn
Published 5/2/2021
Tags: haskell, list, map, functor

Since haskell is a list-based language, there are many ways to work with lists. This article details some of the most interesting ways to multiply each number in a list by 5.

  1. The Imperative way
main:: IO() main = do mutable <- M.replicate 256 1 forM_ ([1..256] z-> modify mutable (x->x*5) z )
  1. The boring way
multiplyList :: [Int] -> [Int] multiplyList xs = map (\x->x*5) xs
  1. currying
multiplyList :: [Int] -> [Int] multiplyList = map (*5)
  1. monad
multiplyList :: [Int] -> [Int] multiplyList xs = xs >>= (\x -> [x*5])
  1. short functor
m=(<$>)(*5)
  1. List comprehension
multiplyList :: [Int] -> [Int] multiplyList xs = [x*5 | x <- xs]
  1. Do notation
multiplyList :: [Int] -> [Int] multiplyList xs = do x <- xs return $ x*5
  1. Functor
multiplyList :: [Int] -> [Int] multiplyList xs = fmap (\x -> x*5) xs
  1. Applicative
multiplyList :: [Int] -> [Int] multiplyList xs = pure (\x->x*5) <*> xs
  1. Recursion
multiplyList :: [Int] -> [Int] multiplyList [] = [] multiplyList (x:xs) = (x*5) : multiplyList xs

Reccomended Articles