Reputation: 275
I want to know how I can get multiple elements in a list in one function
for example if I wanted to get elements 1 2 3 and 4 from list a
, I would have to type a!!0 ++ a!!1 ++ a!!2 ++ a!!3
. This takes up a lot of space especially if the list name is more than one character. so I'm wondering if I can do something like a!![0,1,2,3]
instead and get all of those elements in a much shorter way. Thank you.
Upvotes: 1
Views: 502
Reputation: 476594
You can work with a mapping where you lookup all items for a list, so:
map (a !!) [0,1,2,3]
If you are however interested in the first four items, you can work with take :: Int -> [a] -> [a]
:
take 4 a
especially since looking up by an index (with (!!)
) is not a common operation in Haskell: this is unsafe since it is not guaranteed that the index is in bounds. Most list processing is done with functions like take
, drop
, sum
, foldr
, etc.
Upvotes: 5