Paul
Paul

Reputation: 21975

Finding the position of some substrings in a string

After a bit of hoogle-ing I came up with this:

import Data.List
substrPos xs str = map (\x -> findIndex (isPrefixOf x) $ tails str) xs

That should give me a list of indices that represent the first appearance in str of every string in xs.

E.g.:

Prelude Data.List> substrPos ["Foo", "Bar"] "FooBar"
[Just 0,Just 3]

The question is how can I write it more idiomatic, maybe I can lose the lambda? Maybe somehow (function composition?) remove the parens enclosing isPrefixOf x? Maybe write it in point free style?

How should I go about thinking of these things?

PS: The only modification I could come up with (after first writing the function) is the removal of parens from tails xs by function application.

Upvotes: 1

Views: 796

Answers (1)

Sibi
Sibi

Reputation: 48644

You can always install the pointfree tool and check it for yourself and try to understand the resultant code.

Pointfree tool gives me the following result:

map (($ tails str) . findIndex . isPrefixOf) xs

Although you should note that pointfree style is not always idiomatic. Some people consider it as unreadable and pointless.

Upvotes: 4

Related Questions