You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Haskell中实现返回子串起止索引元组列表的函数

Haskell子串位置索引函数实现

你直接修改参数类型报错的核心原因是原有findPos实现遍历的是单个字符,无法直接和字符串做相等判断,需要调整匹配逻辑为子串前缀匹配。

以下是仅使用Prelude基础特性的实现方案:

完整代码

-- 辅助前缀匹配函数,完全基于Prelude模式匹配实现,无需额外导入包
isPrefixOf :: Eq a => [a] -> [a] -> Bool
isPrefixOf [] _ = True
isPrefixOf _ [] = False
isPrefixOf (x:xs) (y:ys) = x == y && isPrefixOf xs ys

-- 子串位置查找函数,返回所有匹配位置的起止索引元组
findPos :: Eq a => [a] -> [a] -> [(Int, Int)]
findPos sub str = [(i, i + subLen - 1) | i <- [0 .. maxIdx], isPrefixOf sub (drop i str)]
  where
    subLen = length sub
    -- 最大合法起始索引:超过这个值剩余字符长度不足以匹配子串
    maxIdx = length str - subLen

运行效果测试

-- 匹配双字符子串
ghci> findPos "bl" "blablabla" 
[(0,1), (3,4), (6,7)]

-- 匹配示例中的aa子串
ghci> findPos "aa" "foobaarfoobaar"
[(4,5), (11,12)]

-- 兼容原单字符匹配需求(传入单元素列表即可)
ghci> findPos ['b'] "blablabla"
[(0,0),(3,3),(6,6)]

-- 边界场景:子串长度超过目标串返回空
ghci> findPos "abcdef" "abc"
[]

内容的提问来源于stack exchange,提问作者Mampenda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 18:39:03