查找字符串中某些子字符串的位置 [英] Finding the position of some substrings in a string

查看:81
本文介绍了查找字符串中某些子字符串的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过一番讨价还价,我想到了这一点:

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

这应该给我一个索引列表,这些索引代表 xs 中每个字符串在 str 中的首次出现.

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

例如:

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

问题是我该如何写得更惯用,也许我会丢掉lambda?也许以某种方式(函数组合?)删除了包围 isPrefixOf x 的括号?也许以无点样式编写它?

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 :(首先编写函数之后)我唯一能想到的修改是通过函数应用程序从 tails xs 中删除parens.

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.

推荐答案

您始终可以安装 pointfree 工具并亲自检查一下,然后尝试理解生成的代码.

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.

这篇关于查找字符串中某些子字符串的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆