如何计算有序 [Char] 中 Char 的出现次数?

How to calculate the occurrences of Char in an ordered [Char]?

我有一个输入 [String] 如下:

main = do
  let res = calcCounts ["IOIOOIOOI\r","OOIIIOOO\r",...]

我想使用非统一的基础系统 IO 个实例按顺序

我创建了一个 Type:

data OutputState = OutputState { totNumI :: Int,
                                 totNumO :: Int,
                                 numI :: Int,
                                 numO :: Int
                               } deriving (Show)

到目前为止,我创建的代码尝试逐步完成输入并每次创建一个新的 OutputState,同时在达到完成条件 [=19] 之前考虑到之前的 OutputState =] 每个 [Char][String] 的列表结尾但不完整:

calcCounts :: [String] -> [OutputState]
calcCounts input = map genOutputState input

genOutputState :: [Char] -> OutputState
genOutputState (x:xs)
  | x == '\r' = --return final OutputState 
  | otherwise do                 
      let currOutputState = incrementOutputState x
      genOutputState xs --also pass current OutputState back each recursion

incrementOutputState :: OutputState -> Char -> OutputState
incrementOutputState pos@prevOS x = do
  | if x == 'I' = do 
      let currOutputState = OutputState pos{totNumA} pos{totNumB} pos{numA}+1 pos{numB}
      | if currOutputState{numA} == 4 = OutputState currOutputState{totNumA}+1 currOutputState{totNumB} 0 0         
  | otherwise = do 
      let currentOutputState = OutputState pos{totNumA} pos{totNumB} pos{numA} pos{numB}+1
      | if currentOutputState{numB} == 4 = OutputState currOutputState{totNumA} currOutputState{totNumB}+1 0 0

最终输出应该是[OutputState,OutputState,..]

我知道我的代码目前不合法并且缺少逻辑。对此表示歉意。总的来说,我仍在回归 Haskell 和函数式编程的过程中。在命令式范例中,我会使用可变变量来跟踪必要的计数,但我明白这不是从功能意义上考虑问题的正确方法。

非常感谢任何帮助!

我认为这就是你想要做的,尽管我仍然不完全确定我是否理解正确。

data OutputState = OutputState { totNumI :: Int,
                                 totNumO :: Int,
                                 numI :: Int,
                                 numO :: Int
                               } deriving (Show)

genOutputState :: String -> OutputState
genOutputState = foldl incrementOutputState (OutputState 0 0 0 0)

incrementOutputState :: OutputState -> Char -> OutputState
incrementOutputState (OutputState ti to 3 no)  'I' = OutputState (ti + 1) to 0 0
incrementOutputState (OutputState ti to ni no) 'I' = OutputState ti to (ni + 1) no
incrementOutputState (OutputState ti to ni 3)  'O' = OutputState ti (to + 1) 0 0
incrementOutputState (OutputState ti to ni no) 'O' = OutputState ti to ni (no + 1)
incrementOutputState os _                          = os -- Do not increment anything for characters other than 'I' and 'O'

我建议您再学习一些 Haskell 教程,因为我觉得您还不太了解语法和函数式思维方式。