Jozott
Jozott

Reputation: 2674

Haskell get elements from list through list of indices

I have a list of indexes and want to get a list filled with the values obtained by the indexes.

e.g.:

[1,2,3,4] `getAllOf` [1,3] --> [2,4] 

What is the simplest way to do this?

Upvotes: 0

Views: 198

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

It the list of indices is sorted, it is better to use recursion, since then we avoid enumerating multiples times over the list of values:

getAllOf :: [a] -> [Int] -> Maybe [a]
getAllOf = flip (go 0)
    where go _ [] _ = Just []
          go i (j:js) xs
              | j < i = Nothing
              | (y:ys) <- drop (j-i) xs = (y :) <$> go (j+1) js ys
              | otherwise = Nothing

This wraps the result in a Just if all indices are valid, and Nothing otherwise. For example:

Prelude> getAllOf [1..4] [1,3]
Just [2,4]
Prelude> getAllOf [1..4] [1,1]
Nothing
Prelude> getAllOf [1..4] [-1,2]
Nothing
Prelude> getAllOf [1..4] [15]
Nothing
Prelude> getAllOf [1..4] [0,1,2,3,4]
Nothing
Prelude> getAllOf [1..4] [0,1,2,3]
Just [1,2,3,4]

Upvotes: 2

Jozott
Jozott

Reputation: 2674

Using map should be the shortest solution for that.

This is the long version:

map (\x -> [1,2,3,4]!!x) [1,3]

you can simplify it by using:

map ([1,2,3,4]!!) [1,3]

is the short and clean way without lambda expression.

Upvotes: 2

Related Questions