gpt4 book ai didi

haskell - 缩短字符串 Haskell

转载 作者:行者123 更新时间:2023-12-02 10:40:04 24 4
gpt4 key购买 nike

如何在 Haskell 中用给定的数字缩短字符串。

说:

comp :: String -> String
short :: String -> String

chomp (x:xs) = (x : takeWhile (==x) xs)

using comp 我想从字符串的开头选择一系列重复的字符,该运行最多包含九个字符。

例如:

短“aaaavvvdd”将输出“aaaa”短“dddddddddd”输出“dddddddddd”

我知道我需要take,但不知道如何将其放入代码中。

我已经做到了这一点,但它不起作用

short x:xs | length(short x:xs) >9 = take(9)
| otherwise = comp

最佳答案

快速回答

import Data.List
short [] = []
short x = (take 9 . head . group) x

这将为您提供与您所需的输出相匹配的输出。

也就是说,

*> short "aaaavvvdd"
"aaaa"
*> short "dddddddddd"
"ddddddddd"
<小时/>

逐步开发

使用“group”分隔项目

此解决方案依赖于 Data.List 库中的“group”函数。我们从定义开始:

short x = group x

这给了我们:

*> short "aaaavvvddd"
["aaaa","vvv","ddd"]

使用“head”仅返回第一个元素

一旦我们有了列表中的元素,我们只需要列表的第一项。我们使用“head”来实现这一点:

short x = (head . group) x

“。”是用于函数组合的 Haskell 函数。它等同于:

short x = head (group x)

short x = head $ group x

这将为我们提供:

*> short "aaaavvvdd"
"aaaa"
*> short "dddddddddddddd"
"dddddddddddddd"

使用“take”获取前九个字符

我们通过只取结果的前九个字符来完成程序,并最终得到我们的最终函数。为此,我们使用前奏中的“take”函数:

short x = (take 9 . head . group) x

我们现在得到了我们想要的结果,但有一个小问题。

添加另一个案例以消除错误

请注意,在空列表上使用我们当前的定义会导致错误,

*> short "aaaavvvddd"
"aaaa"
*> short ""
"*** Exception: Prelude.head: empty list

因为“head”在空列表上未定义,所以我们需要处理另一种情况:空列表。现在我们有:

short [] = []
short x = (take 9 . head . group) x

这是我们的“最终答案”。

关于haskell - 缩短字符串 Haskell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5185351/

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