Haskell - 字符串压缩

Mar*_*scu 1 haskell functional-programming

我是 Haskell 的新手,我正在尝试编写一个函数,将字符串压缩为字符 + 该字符连续出现的次数,例如:aaaabccc -> a4bc3

到目前为止,我得到了类似的东西:

comp :: String -> Int -> String
comp [] n =[]

comp (x:x1:xs) ct = if(x==x1) then comp (x1:ct:xs) (ct+1) else if(ct>0) then comp (x1:xs) (0) else comp (x1:xs) (0)
comp (x:xs) n = x:xs



main = do
        a <- getLine
        putStrLn $ comp a 0 
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误

main.cpp:4:45:
    Couldn't match expected type `Char' with actual type `Int'
    In the first argument of `(:)', namely `ct'
    In the second argument of `(:)', namely `ct : xs'
    In the first argument of `comp', namely `(x1 : ct : xs)'
Run Code Online (Sandbox Code Playgroud)

Bar*_*icz 5

您正在尝试将 an 附加Int到 a String;您需要明确地将其转换为String第一个;改变:

comp (x1:ct:xs)
Run Code Online (Sandbox Code Playgroud)

comp (x1 : show ct ++ xs)
Run Code Online (Sandbox Code Playgroud)