Reputation: 2967
I have the following function that searches through [Char] and returns [Char] based on their index number:
myList = "abcdefghijk"
searchText = foldl (\acc el -> if elemIndex el myList > Just 11 then el : acc else acc) [] myList
Clearly this is somewhat inefficent as elemIndex returns the index number of each element then applies the condition.
Is there a more efficient way of performing this operation?
Upvotes: 0
Views: 88
Reputation: 36375
Your function returns a string that skips the first twelve characters and reverses the output, dropping any characters that are also in those first twelve.
For a more efficient version of this, you could use Data.Set
to store those first twelve characters for fast lookup, the filter them out and reverse the remainder of the string:
import qualified Data.Set as Set
searchText =
let hash = (Set.fromList . take 12) myList
in (reverse . filter (flip Set.notMember hash) . drop 12) myList
Upvotes: 1
Reputation: 116139
The usual approach is to pair each character with its index before doing the real processing
process $ zip [0..] myList
Now process
can perform the actual computation, which can use the indexes as well as the characters.
In some contexts, this approach is known as the Schwartzian transform.
Upvotes: 2