string - 如何比较 Haskell 中同一列表中的多个字符串

标签 string list haskell recursion functional-programming

我正在尝试编写一个 Haskell 函数,它接受一个字符串列表,比较列表中的所有字符串,并输出一个长度最长的字符串列表。我想在没有任何预定义函数或导入的情况下执行此操作,我想尝试递归地解决所有问题。例如:

    longeststrings["meow","cats","dog","woof"] -> ["meow","cats","woof"]

我知道这是一个愚蠢的例子,但我认为它证明了这一点。

我想做类似的事情

    longeststrings:: [string] -> [string]
    longeststrings []          = []
    longeststrings [x:xs]      = if (x > xs) x:longeststrings[xs]

但我不知道如何只从列表中取出最大的字符串,或删除最小的字符串。如果有任何帮助,我将不胜感激。

最佳答案

您可以简单地跟踪最长长度的字符串和该长度值的累加器。

longestStrings :: [String] -> [String]
longestStrings = go [] 0
  where
  go acc _ []       = acc  -- base case
  go acc n (x:xs)
    | length x > n  = go [x] (length x) xs
    -- if x is longer than the previously-seen longest string, then set
    -- accumulator to the list containing only x, set the longest length
    -- to length x, and keep looking
    | length x == n = go (x:acc) n xs
    -- if x is the same length as the previously-seen longest string, then
    -- add it to the accumulator and keep looking
    | otherwise     = go acc n xs
    -- otherwise, ignore it

或者,正如 Davislor 在评论中正确提到的那样,这可以通过教辅助函数确定其最长长度来实现为折叠

longestStrings :: [String] -> [String]
longestStrings = foldr f []
  where
  f x []        = [x]
  f x yss@(y:_) =
    case compare (length x) (length y) of
      GT -> [x]
      EQ -> x : yss
      LT -> yss

关于string - 如何比较 Haskell 中同一列表中的多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48713997/

相关文章:

Python:检查生成器中是否存在对象

python - 动态嵌套字典 Python

haskell - hdevtools 在 7.8.3 平台上安装失败

java - 初始化后向空字符串添加字符

java - 无法使用beanshell在jmeter中重命名具有动态路径的文件

java - 字符串有麻烦

python - 遍历 2 个列表并构建相对字典的有效方法

haskell - 在 Haskell 中检测图的循环(可能有向或无向)

haskell - 对不同大小的输入运行 Haskell 基准测试

c - 是否有 C 函数将以 X 为基数的数字字符串转换为以 Y 为基数的字符串?