10 Common JavaScript Array Methods & Their Haskell List Counterparts

Using the Data.List Module

Manipulating arrays and lists are a big part of coding. Coming from JavaScript I was spoiled with the many many built-in array functions available. From map to sort to filter. These are basic building blocks I needed to continue coding in Haskell. That's when I came across the Data.List module.

Data.List

Data.List is a Haskell module, or a collection of related functions, types, and typeclasses. This module contains many useful functions for dealing with lists. To import the module, simply include the following at the top of your file (before you use any of the functions from the module):

import Data.List

Now let's see how some of the most common Javascript array functions can be translated to Haskell using the functions available to us in Data.List. See here for details on all the available functions in Data.List

1. array.map()

map :: (a -> b) -> [a] -> [b]>>> map (+1) [1, 2, 3]
[2,3,4]

2. array.reduce()

foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b>>> foldl (+) 0 [1,2,3,4]
10

3. array.filter()

filter :: (a -> Bool) -> [a] -> [a]>>> filter (< 2) [1, 2, 3]
[1]

4. array.find()

find :: Foldable t => (a -> Bool) -> t a -> Maybe a>>> find (>2) [1,2,3,4,5]
Just 3

5. array.some()

any :: Foldable t => (a -> Bool) -> t a -> Bool>>> any (> 4) [1,2,3,4,5]
True

6. array.every()

all :: Foldable t => (a -> Bool) -> t a -> Bool>>> all (> 3) [1,2,3,4,5]
False

7. array.indexOf()

elemIndex :: Eq a => a -> [a] -> Maybe Int>>> elemIndex 4 [1, 4, 7, 9]
Just 1

8. array.includes()

elem :: (Foldable t, Eq a) => a -> t a -> Bool>>> 3 `elem` [1,2,3,4,5]
True

9. array.sort()

sort :: Ord a => [a] -> [a]>>> sort [1,6,4,3,1]
[1,1,3,4,6]

10. array.slice()

Unfortunately, there is no JavaScript’s slice equivalent in Data.List but we can use the functions drop and take to define our own slice function in Haskell.

drop :: Int -> [a] -> [a]>>> drop 3 [1,2,3,4,5]
[4,5]
take :: Int -> [a] -> [a]>>> take 3 [1,2,3,4,5]
[1,2,3]
slice' :: Int -> Int -> [a] -> [a]
slice' start end xs = take (end - start + 1) (drop start xs)

References:

I love seafood, exploring new cities, board games and learning to love to code. https://github.com/sarakhandaker/portfolio