使用 haskell 过滤以“ed”或“ing”结尾的单词

296*_*349 2 haskell

你好,我是 Haskell 和函数式编程的新手。

我想传入字符串并找到以“ed”或“ing”结尾的单词。

eg: if the string is "he is playing and he played well"
answer should be : playing, played
Run Code Online (Sandbox Code Playgroud)

有谁知道如何使用 Haskell 来做到这一点。

Gar*_*thR 5

您可以使用标准 Haskell 函数构建它。首先导入 Data.List:

import Data.List
Run Code Online (Sandbox Code Playgroud)

用于isSuffixOf确定一个列表是否以另一个列表结尾。下面endings可能["ed","ing"]w您正在测试的单词,例如"played"

hasEnding endings w = any (`isSuffixOf` w) endings
Run Code Online (Sandbox Code Playgroud)

假设您已将字符串拆分为单个单词的列表(ws如下),请使用filter来消除您不需要的单词:

wordsWithEndings endings ws = filter (hasEnding endings) ws
Run Code Online (Sandbox Code Playgroud)

用于words从原始字符串中获取单词列表。用于intercalculate将过滤后的单词连接回最终的逗号分隔字符串(或者如果您希望结果作为单词列表,则将其保留)。用于.将这些函数链接在一起。

wordsEndingEdOrIng ws = intercalate ", " . wordsWithEndings ["ed","ing"] . words $ ws
Run Code Online (Sandbox Code Playgroud)

你就完成了。

wordsEndingEdOrIng "he is playing and he played well"
Run Code Online (Sandbox Code Playgroud)

如果您在 ghci 中输入,请将其放在let每个函数定义的前面(除最后一行之外的所有行)。