gpt4 book ai didi

haskell - 使用haskell过滤以 "ed"或 "ing"结尾的单词

转载 作者:行者123 更新时间:2023-12-05 02:23:33 25 4
gpt4 key购买 nike

嗨,我是 Haskell 和函数式编程的新手..

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

eg: if the string is "he is playing and he played well"
answer should be : playing, played

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

最佳答案

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

import Data.List

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

hasEnding endings w = any (`isSuffixOf` w) endings

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

wordsWithEndings endings ws = filter (hasEnding endings) ws

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

wordsEndingEdOrIng ws = intercalate ", " . wordsWithEndings ["ed","ing"] . words $ ws

你就完成了。

wordsEndingEdOrIng "he is playing and he played well"

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

关于haskell - 使用haskell过滤以 "ed"或 "ing"结尾的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21017923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com