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

问题描述 投票:0回答:1

我有一个输入 [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 每一次,同时考虑到之前的 OutputState 在达到完成条件之前,这是 '\r' 对于每个 [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和一般的函数式编程的过程中。在命令式范式中,我将利用可变变量来跟踪必要的计数,但我明白这不是在函数式意义上思考问题的正确方式。

任何帮助都是非常感激的

haskell recursion functional-programming conditional-statements immutability
1个回答
1
投票

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

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的教程,因为我感觉你还不太理解语法和函数的思维方式。

© www.soinside.com 2019 - 2024. All rights reserved.