如何找到以给定前缀开头的字符串列表的字符串?

发布于 2025-02-11 18:43:38 字数 398 浏览 1 评论 0原文

我想编写一个可以返回字符串列表的辅助函数

helper ['Excuse','Me', 'Exit', 'And'] 'Ex' 

,这应该返回

['Excuse','Exit']

我搜索并在data.list中找到isinfixof函数可以比较两个字符串,但是我如何递归调用以找到正确的字符串列表

helper :: [String] -> String -> [String]
helper [] _ = []  
helper (x:xs) std 
    | isInfixOf x std == True : helper

I want to write a helper function that could return a string list

helper ['Excuse','Me', 'Exit', 'And'] 'Ex' 

and this should return

['Excuse','Exit']

I search up and find in Data.List have the isInfixOf function could compare two string, but how could I recursive call to find the correct String list

helper :: [String] -> String -> [String]
helper [] _ = []  
helper (x:xs) std 
    | isInfixOf x std == True : helper

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

宫墨修音 2025-02-18 18:43:38

你几乎完全在那里。

在列表上调用helper [“借口”,“我”,“退出”,“”和“] nath ,您要写:

helper myList "Ex"

现在,当您将该列表与x:xsxs匹配时,这只是另一个列表。要调用助手对此递归,您只需编写helper XS std即可。

您无需明确将iSinfixof的返回与true进行比较。您还需要处理isinfixof x std is true的情况。

helper :: [String] -> String -> [String]
helper [] _ = []  
helper (x:xs) std 
    | isInfixOf x std = x : helper xs std
    | otherwise = helper xs std

You're almost entirely there.

To call helper on a list ["Excuse", "Me", "Exit", "And"] named, oh let's say myList, you'd write:

helper myList "Ex"

Now, when you pattern match that list with x:xs, xs is the tail of the list, which is just another list. To call helper recursively on this, you'd just write helper xs std.

You do not need to explicitly compare the return of isInfixOf to True. You also need to handle the case where isInfixOf x std is not true.

helper :: [String] -> String -> [String]
helper [] _ = []  
helper (x:xs) std 
    | isInfixOf x std = x : helper xs std
    | otherwise = helper xs std
萌吟 2025-02-18 18:43:38

实际上,没有理由使用递归功能来做到这一点。您想保留满足特定谓词的列表的元素(“ ex”是元素的插图)。 filt> filter功能做到这一点。

import Data.List (isInfixOf)

helper :: Eq a => [[a]] -> [a] -> [[a]]
helper = flip (filter . isInfixOf)

例如:

helper ["Excuse", "Me", "Exit", "And"] "Ex"
-- ["Excuse","Exit"]

There is not really a reason to do that with a recursive function. You want to keep elements of a list that fulfill a certain predicate ("Ex" being an infix of the element). The filter function does exactly that.

import Data.List (isInfixOf)

helper :: Eq a => [[a]] -> [a] -> [[a]]
helper = flip (filter . isInfixOf)

For example:

helper ["Excuse", "Me", "Exit", "And"] "Ex"
-- ["Excuse","Exit"]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文