例如:?aaaabbaab?->[('a',4),('b',2),('a',2),('b',1)] 需要通過FOLDR通過一次串列,不使用 ( )。
到目前為止我所擁有的
task2 (x:xs) = foldr (\c [(symbol, count)] -> if symbol == c then [(symbol, count 1)] else [(symbol, count)]) [(x, 1)] xs
問題是我真的不明白如何在 'if' 陳述句為 False 之后讓它轉到串列的下一個元素
uj5u.com熱心網友回復:
將 step 函式撰寫為行內 lambda 運算式可能不是最好的做法。它可以作業,但這會導致很長的代碼行。
單獨撰寫階躍函式更容易,像這樣:
task2 :: String -> [(Char,Int)]
task2 cs = foldr stepFn [] cs
where
stepFn c [] = [(c,1)] -- simple case
stepFn c ((c1,n1) : ps) = -- please try to write the rest ...
if (c == c1) then (c1,1 n1) : ps else (c,1) : (c1,n1) : ps
測驗:
$ ghci
GHCi, version 8.8.4: https://www.haskell.org/ghc/ :? for help
λ>
λ> :load q69871708.hs
[1 of 1] Compiling Main ( q69871708.hs, interpreted )
Ok, one module loaded.
λ>
λ> task2 "aaaabbaabrrrzz"
[('a',4),('b',2),('a',2),('b',1),('r',3),('z',2)]
λ>
λ> task2 "a"
[('a',1)]
λ>
λ> task2 ""
[]
λ>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/359172.html
