计算Haskell列表中元素的出现并返回最大序列 [英] Count occurrence of an element in Haskell list and return max sequence

查看:71
本文介绍了计算Haskell列表中元素的出现并返回最大序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  data Elem = Vanilla | 

我有以下代码来计算Haskell列表中元素的出现次数。 Choco派生(Eq,Show)
maxStarSeq :: [Elem] - > Int
maxStarSeq [] = 0
maxStarSeq(Vanilla:xs)= 0 + maxStarSeq xs
maxStarSeq(Choco:xs)= 1 + maxStarSeq xs

现在,我该如何返回该元素的最大序列,而不是绝对计数器?我的意思是,假设我的名单是:

$ p $ [Vanilla,Choco,Choco,Vanilla,Choco]

使用我的代码,我会得到3,因为列表中有3个Choco字符。我想要的是获得2,因为这是Choco字符的最大序列,而下一个序列更短。



我需要的是某种方式来进行比较你可以使用 worker wrapper 模式来达到您所需的结果:

  maxStarSeq :: [Elem]  - > Int 
maxStarSeq xs = aux xs 0 0
其中aux [] acc prev = max acc prev
aux(Vanilla:xs)acc prev = aux xs(max acc prev)0
aux(Choco:xs)acc prev = aux xs acc(prev + 1)

prev 参数将跟踪连续的 Choco 参数的当前数量。 acc 参数的最大数量为 Choco 参数。每次遇到 Vanilla 值时,它的值都会更新。


I have the following code to count the occurrence of an element in a Haskell list:

data Elem = Vanilla | Choco deriving (Eq,Show)
maxStarSeq :: [Elem] -> Int
maxStarSeq [] = 0
maxStarSeq (Vanilla:xs) = 0 + maxStarSeq xs
maxStarSeq (Choco:xs) = 1 + maxStarSeq xs

Now, how can I return the max sequence of that element, instead of an absolute counter? I mean, let's say that my list is:

[Vanilla,Choco,Choco,Vanilla,Choco]

With my code, I will get 3 because there are 3 Choco characters in the list. What I want is to get 2, because that is the max sequence of Choco characters, while the next sequence is shorter.

What I need is some way to make a comparison between the sequences, to evaluate which is longer, or something like that.

解决方案

You can use worker wrapper pattern to achieve your required result:

maxStarSeq :: [Elem] -> Int
maxStarSeq xs = aux xs 0 0
    where aux [] acc prev = max acc prev
          aux (Vanilla:xs) acc prev = aux xs (max acc prev) 0
          aux (Choco:xs) acc prev = aux xs acc (prev + 1)

The prev parameter will track the current number of consecutive Choco parameters. The acc parameter will have the maximum number of Choco parameters for it's previous run. It's value will be updated each time you encounter Vanilla value.

这篇关于计算Haskell列表中元素的出现并返回最大序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆