您好,我們必須創建一個代碼,例如將“1T3e1s1t”轉換為 [(1,'T'),(3,'e'),(1,'s'),(1,'t')]
這是我的代碼
unformat :: String -> [(Int, Char)]
unformat [] = []
unformat (x:xs) = [(unformat' 1, x)] unformat xss
where
unformat' = length (takeWhile (== x)xs)
xss = drop unformat' xs
它可以作業,但輸出是 "1T3e" -> [(1,'1'),(1,'T'),(1,'3'),(1,'e')] 而不是 takeWhile - drop功能我得到錯誤。我也嘗試過使用功能復制但再次輸出錯誤
unformat :: String -> [(Int, Char)]
unformat [] = []
unformat (x:xs) = (replicate (fst x) (snd x)) unformat xs
我真誠地感謝任何形式的幫助
uj5u.com熱心網友回復:
您也可以通過串列開頭的多個元素進行模式匹配(如a:b:xs):
module Main where
import Data.Char
main = print $ unformat "1T3e1s1t" -- [(1,'T'),(3,'e'),(1,'s'),(1,'t')]
unformat :: String -> [(Int, Char)]
unformat (i:c:xs) = (digitToInt i, c) : unformat xs
unformat _ = []
Data.Char.digitToInt例如,轉換'0'為0和。'f'15
uj5u.com熱心網友回復:
這是我的解決方案foldl。在每一步中,我們將 prev chars 記住為Jsut c它是元組的第一項還是元組Nothing的第二項。
module Main where
import Data.Char
main :: IO ()
main = print $ unformat "1T3e1s1t"
unformat :: String -> [(Int, Char)]
unformat s = snd $ foldl opr (Nothing , []) s
where
opr (prev, acc) c = case prev of
Just n -> (Nothing, acc [(digitToInt n, c)])
Nothing -> (Just c, acc)
輸出將是:
[(1,'T'),(3,'e'),(1,'s'),(1,'t')]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/417810.html
標籤:
下一篇:從字串中消除連續重復
